// Force strict mode and setup for ESM
"use strict";
import {
  SUPPORTED_LANGUAGES,
  detectSystemLanguage,
  getLanguageNameFromLocale,
  getLanguageSettingsOptions,
  t,
  writeStderrLine
} from "./chunk-OZVBUTNK.js";
import {
  DEFAULT_STOP_HOOK_BLOCK_CAP,
  DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,
  DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
  DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
  IdeClient,
  SkillError,
  ideContextStore,
  require_main,
  resolveModelConfig,
  stripRuntimeSnapshotPrefix
} from "./chunk-K4WOAR4V.js";
import {
  external_exports
} from "./chunk-K5PGHDBN.js";
import {
  DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES
} from "./chunk-EEEZIVFJ.js";
import {
  AuthType,
  MODEL_GENERATION_CONFIG_FIELDS,
  isWithinRoot
} from "./chunk-O7HNDMMU.js";
import {
  atomicWriteFileSync
} from "./chunk-3UALQ56H.js";
import {
  FatalConfigError,
  QWEN_DIR,
  Storage,
  createDebugLogger,
  getErrorMessage
} from "./chunk-C4K3FEQ2.js";
import {
  init_esbuild_shims
} from "./chunk-A4BMJM77.js";
import {
  __commonJS,
  __name,
  __require,
  __toESM
} from "./chunk-J2S4EL5Y.js";

// node_modules/esprima/dist/esprima.js
var require_esprima = __commonJS({
  "node_modules/esprima/dist/esprima.js"(exports, module) {
    init_esbuild_shims();
    (/* @__PURE__ */ __name(function webpackUniversalModuleDefinition(root, factory) {
      if (typeof exports === "object" && typeof module === "object")
        module.exports = factory();
      else if (typeof define === "function" && define.amd)
        define([], factory);
      else if (typeof exports === "object")
        exports["esprima"] = factory();
      else
        root["esprima"] = factory();
    }, "webpackUniversalModuleDefinition"))(exports, function() {
      return (
        /******/
        function(modules) {
          var installedModules = {};
          function __webpack_require__(moduleId) {
            if (installedModules[moduleId])
              return installedModules[moduleId].exports;
            var module2 = installedModules[moduleId] = {
              /******/
              exports: {},
              /******/
              id: moduleId,
              /******/
              loaded: false
              /******/
            };
            modules[moduleId].call(module2.exports, module2, module2.exports, __webpack_require__);
            module2.loaded = true;
            return module2.exports;
          }
          __name(__webpack_require__, "__webpack_require__");
          __webpack_require__.m = modules;
          __webpack_require__.c = installedModules;
          __webpack_require__.p = "";
          return __webpack_require__(0);
        }([
          /* 0 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var comment_handler_1 = __webpack_require__(1);
            var jsx_parser_1 = __webpack_require__(3);
            var parser_1 = __webpack_require__(8);
            var tokenizer_1 = __webpack_require__(15);
            function parse4(code, options, delegate) {
              var commentHandler = null;
              var proxyDelegate = /* @__PURE__ */ __name(function(node, metadata) {
                if (delegate) {
                  delegate(node, metadata);
                }
                if (commentHandler) {
                  commentHandler.visit(node, metadata);
                }
              }, "proxyDelegate");
              var parserDelegate = typeof delegate === "function" ? proxyDelegate : null;
              var collectComment = false;
              if (options) {
                collectComment = typeof options.comment === "boolean" && options.comment;
                var attachComment = typeof options.attachComment === "boolean" && options.attachComment;
                if (collectComment || attachComment) {
                  commentHandler = new comment_handler_1.CommentHandler();
                  commentHandler.attach = attachComment;
                  options.comment = true;
                  parserDelegate = proxyDelegate;
                }
              }
              var isModule = false;
              if (options && typeof options.sourceType === "string") {
                isModule = options.sourceType === "module";
              }
              var parser;
              if (options && typeof options.jsx === "boolean" && options.jsx) {
                parser = new jsx_parser_1.JSXParser(code, options, parserDelegate);
              } else {
                parser = new parser_1.Parser(code, options, parserDelegate);
              }
              var program = isModule ? parser.parseModule() : parser.parseScript();
              var ast = program;
              if (collectComment && commentHandler) {
                ast.comments = commentHandler.comments;
              }
              if (parser.config.tokens) {
                ast.tokens = parser.tokens;
              }
              if (parser.config.tolerant) {
                ast.errors = parser.errorHandler.errors;
              }
              return ast;
            }
            __name(parse4, "parse");
            exports2.parse = parse4;
            function parseModule(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "module";
              return parse4(code, parsingOptions, delegate);
            }
            __name(parseModule, "parseModule");
            exports2.parseModule = parseModule;
            function parseScript(code, options, delegate) {
              var parsingOptions = options || {};
              parsingOptions.sourceType = "script";
              return parse4(code, parsingOptions, delegate);
            }
            __name(parseScript, "parseScript");
            exports2.parseScript = parseScript;
            function tokenize(code, options, delegate) {
              var tokenizer = new tokenizer_1.Tokenizer(code, options);
              var tokens;
              tokens = [];
              try {
                while (true) {
                  var token = tokenizer.getNextToken();
                  if (!token) {
                    break;
                  }
                  if (delegate) {
                    token = delegate(token);
                  }
                  tokens.push(token);
                }
              } catch (e) {
                tokenizer.errorHandler.tolerate(e);
              }
              if (tokenizer.errorHandler.tolerant) {
                tokens.errors = tokenizer.errors();
              }
              return tokens;
            }
            __name(tokenize, "tokenize");
            exports2.tokenize = tokenize;
            var syntax_1 = __webpack_require__(2);
            exports2.Syntax = syntax_1.Syntax;
            exports2.version = "4.0.1";
          },
          /* 1 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var CommentHandler = function() {
              function CommentHandler2() {
                this.attach = false;
                this.comments = [];
                this.stack = [];
                this.leading = [];
                this.trailing = [];
              }
              __name(CommentHandler2, "CommentHandler");
              CommentHandler2.prototype.insertInnerComments = function(node, metadata) {
                if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) {
                  var innerComments = [];
                  for (var i = this.leading.length - 1; i >= 0; --i) {
                    var entry = this.leading[i];
                    if (metadata.end.offset >= entry.start) {
                      innerComments.unshift(entry.comment);
                      this.leading.splice(i, 1);
                      this.trailing.splice(i, 1);
                    }
                  }
                  if (innerComments.length) {
                    node.innerComments = innerComments;
                  }
                }
              };
              CommentHandler2.prototype.findTrailingComments = function(metadata) {
                var trailingComments = [];
                if (this.trailing.length > 0) {
                  for (var i = this.trailing.length - 1; i >= 0; --i) {
                    var entry_1 = this.trailing[i];
                    if (entry_1.start >= metadata.end.offset) {
                      trailingComments.unshift(entry_1.comment);
                    }
                  }
                  this.trailing.length = 0;
                  return trailingComments;
                }
                var entry = this.stack[this.stack.length - 1];
                if (entry && entry.node.trailingComments) {
                  var firstComment = entry.node.trailingComments[0];
                  if (firstComment && firstComment.range[0] >= metadata.end.offset) {
                    trailingComments = entry.node.trailingComments;
                    delete entry.node.trailingComments;
                  }
                }
                return trailingComments;
              };
              CommentHandler2.prototype.findLeadingComments = function(metadata) {
                var leadingComments = [];
                var target;
                while (this.stack.length > 0) {
                  var entry = this.stack[this.stack.length - 1];
                  if (entry && entry.start >= metadata.start.offset) {
                    target = entry.node;
                    this.stack.pop();
                  } else {
                    break;
                  }
                }
                if (target) {
                  var count = target.leadingComments ? target.leadingComments.length : 0;
                  for (var i = count - 1; i >= 0; --i) {
                    var comment = target.leadingComments[i];
                    if (comment.range[1] <= metadata.start.offset) {
                      leadingComments.unshift(comment);
                      target.leadingComments.splice(i, 1);
                    }
                  }
                  if (target.leadingComments && target.leadingComments.length === 0) {
                    delete target.leadingComments;
                  }
                  return leadingComments;
                }
                for (var i = this.leading.length - 1; i >= 0; --i) {
                  var entry = this.leading[i];
                  if (entry.start <= metadata.start.offset) {
                    leadingComments.unshift(entry.comment);
                    this.leading.splice(i, 1);
                  }
                }
                return leadingComments;
              };
              CommentHandler2.prototype.visitNode = function(node, metadata) {
                if (node.type === syntax_1.Syntax.Program && node.body.length > 0) {
                  return;
                }
                this.insertInnerComments(node, metadata);
                var trailingComments = this.findTrailingComments(metadata);
                var leadingComments = this.findLeadingComments(metadata);
                if (leadingComments.length > 0) {
                  node.leadingComments = leadingComments;
                }
                if (trailingComments.length > 0) {
                  node.trailingComments = trailingComments;
                }
                this.stack.push({
                  node,
                  start: metadata.start.offset
                });
              };
              CommentHandler2.prototype.visitComment = function(node, metadata) {
                var type = node.type[0] === "L" ? "Line" : "Block";
                var comment = {
                  type,
                  value: node.value
                };
                if (node.range) {
                  comment.range = node.range;
                }
                if (node.loc) {
                  comment.loc = node.loc;
                }
                this.comments.push(comment);
                if (this.attach) {
                  var entry = {
                    comment: {
                      type,
                      value: node.value,
                      range: [metadata.start.offset, metadata.end.offset]
                    },
                    start: metadata.start.offset
                  };
                  if (node.loc) {
                    entry.comment.loc = node.loc;
                  }
                  node.type = type;
                  this.leading.push(entry);
                  this.trailing.push(entry);
                }
              };
              CommentHandler2.prototype.visit = function(node, metadata) {
                if (node.type === "LineComment") {
                  this.visitComment(node, metadata);
                } else if (node.type === "BlockComment") {
                  this.visitComment(node, metadata);
                } else if (this.attach) {
                  this.visitNode(node, metadata);
                }
              };
              return CommentHandler2;
            }();
            exports2.CommentHandler = CommentHandler;
          },
          /* 2 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            exports2.Syntax = {
              AssignmentExpression: "AssignmentExpression",
              AssignmentPattern: "AssignmentPattern",
              ArrayExpression: "ArrayExpression",
              ArrayPattern: "ArrayPattern",
              ArrowFunctionExpression: "ArrowFunctionExpression",
              AwaitExpression: "AwaitExpression",
              BlockStatement: "BlockStatement",
              BinaryExpression: "BinaryExpression",
              BreakStatement: "BreakStatement",
              CallExpression: "CallExpression",
              CatchClause: "CatchClause",
              ClassBody: "ClassBody",
              ClassDeclaration: "ClassDeclaration",
              ClassExpression: "ClassExpression",
              ConditionalExpression: "ConditionalExpression",
              ContinueStatement: "ContinueStatement",
              DoWhileStatement: "DoWhileStatement",
              DebuggerStatement: "DebuggerStatement",
              EmptyStatement: "EmptyStatement",
              ExportAllDeclaration: "ExportAllDeclaration",
              ExportDefaultDeclaration: "ExportDefaultDeclaration",
              ExportNamedDeclaration: "ExportNamedDeclaration",
              ExportSpecifier: "ExportSpecifier",
              ExpressionStatement: "ExpressionStatement",
              ForStatement: "ForStatement",
              ForOfStatement: "ForOfStatement",
              ForInStatement: "ForInStatement",
              FunctionDeclaration: "FunctionDeclaration",
              FunctionExpression: "FunctionExpression",
              Identifier: "Identifier",
              IfStatement: "IfStatement",
              ImportDeclaration: "ImportDeclaration",
              ImportDefaultSpecifier: "ImportDefaultSpecifier",
              ImportNamespaceSpecifier: "ImportNamespaceSpecifier",
              ImportSpecifier: "ImportSpecifier",
              Literal: "Literal",
              LabeledStatement: "LabeledStatement",
              LogicalExpression: "LogicalExpression",
              MemberExpression: "MemberExpression",
              MetaProperty: "MetaProperty",
              MethodDefinition: "MethodDefinition",
              NewExpression: "NewExpression",
              ObjectExpression: "ObjectExpression",
              ObjectPattern: "ObjectPattern",
              Program: "Program",
              Property: "Property",
              RestElement: "RestElement",
              ReturnStatement: "ReturnStatement",
              SequenceExpression: "SequenceExpression",
              SpreadElement: "SpreadElement",
              Super: "Super",
              SwitchCase: "SwitchCase",
              SwitchStatement: "SwitchStatement",
              TaggedTemplateExpression: "TaggedTemplateExpression",
              TemplateElement: "TemplateElement",
              TemplateLiteral: "TemplateLiteral",
              ThisExpression: "ThisExpression",
              ThrowStatement: "ThrowStatement",
              TryStatement: "TryStatement",
              UnaryExpression: "UnaryExpression",
              UpdateExpression: "UpdateExpression",
              VariableDeclaration: "VariableDeclaration",
              VariableDeclarator: "VariableDeclarator",
              WhileStatement: "WhileStatement",
              WithStatement: "WithStatement",
              YieldExpression: "YieldExpression"
            };
          },
          /* 3 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            var __extends = this && this.__extends || function() {
              var 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 function(d, b) {
                extendStatics(d, b);
                function __() {
                  this.constructor = d;
                }
                __name(__, "__");
                d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
              };
            }();
            Object.defineProperty(exports2, "__esModule", { value: true });
            var character_1 = __webpack_require__(4);
            var JSXNode = __webpack_require__(5);
            var jsx_syntax_1 = __webpack_require__(6);
            var Node = __webpack_require__(7);
            var parser_1 = __webpack_require__(8);
            var token_1 = __webpack_require__(13);
            var xhtml_entities_1 = __webpack_require__(14);
            token_1.TokenName[
              100
              /* Identifier */
            ] = "JSXIdentifier";
            token_1.TokenName[
              101
              /* Text */
            ] = "JSXText";
            function getQualifiedElementName(elementName) {
              var qualifiedName;
              switch (elementName.type) {
                case jsx_syntax_1.JSXSyntax.JSXIdentifier:
                  var id = elementName;
                  qualifiedName = id.name;
                  break;
                case jsx_syntax_1.JSXSyntax.JSXNamespacedName:
                  var ns = elementName;
                  qualifiedName = getQualifiedElementName(ns.namespace) + ":" + getQualifiedElementName(ns.name);
                  break;
                case jsx_syntax_1.JSXSyntax.JSXMemberExpression:
                  var expr = elementName;
                  qualifiedName = getQualifiedElementName(expr.object) + "." + getQualifiedElementName(expr.property);
                  break;
                /* istanbul ignore next */
                default:
                  break;
              }
              return qualifiedName;
            }
            __name(getQualifiedElementName, "getQualifiedElementName");
            var JSXParser = function(_super) {
              __extends(JSXParser2, _super);
              function JSXParser2(code, options, delegate) {
                return _super.call(this, code, options, delegate) || this;
              }
              __name(JSXParser2, "JSXParser");
              JSXParser2.prototype.parsePrimaryExpression = function() {
                return this.match("<") ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this);
              };
              JSXParser2.prototype.startJSX = function() {
                this.scanner.index = this.startMarker.index;
                this.scanner.lineNumber = this.startMarker.line;
                this.scanner.lineStart = this.startMarker.index - this.startMarker.column;
              };
              JSXParser2.prototype.finishJSX = function() {
                this.nextToken();
              };
              JSXParser2.prototype.reenterJSX = function() {
                this.startJSX();
                this.expectJSX("}");
                if (this.config.tokens) {
                  this.tokens.pop();
                }
              };
              JSXParser2.prototype.createJSXNode = function() {
                this.collectComments();
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.createJSXChildNode = function() {
                return {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              };
              JSXParser2.prototype.scanXHTMLEntity = function(quote) {
                var result = "&";
                var valid = true;
                var terminated = false;
                var numeric = false;
                var hex = false;
                while (!this.scanner.eof() && valid && !terminated) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === quote) {
                    break;
                  }
                  terminated = ch === ";";
                  result += ch;
                  ++this.scanner.index;
                  if (!terminated) {
                    switch (result.length) {
                      case 2:
                        numeric = ch === "#";
                        break;
                      case 3:
                        if (numeric) {
                          hex = ch === "x";
                          valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0));
                          numeric = numeric && !hex;
                        }
                        break;
                      default:
                        valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0)));
                        valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0)));
                        break;
                    }
                  }
                }
                if (valid && terminated && result.length > 2) {
                  var str = result.substr(1, result.length - 2);
                  if (numeric && str.length > 1) {
                    result = String.fromCharCode(parseInt(str.substr(1), 10));
                  } else if (hex && str.length > 2) {
                    result = String.fromCharCode(parseInt("0" + str.substr(1), 16));
                  } else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) {
                    result = xhtml_entities_1.XHTMLEntities[str];
                  }
                }
                return result;
              };
              JSXParser2.prototype.lexJSX = function() {
                var cp = this.scanner.source.charCodeAt(this.scanner.index);
                if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) {
                  var value = this.scanner.source[this.scanner.index++];
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index - 1,
                    end: this.scanner.index
                  };
                }
                if (cp === 34 || cp === 39) {
                  var start = this.scanner.index;
                  var quote = this.scanner.source[this.scanner.index++];
                  var str = "";
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source[this.scanner.index++];
                    if (ch === quote) {
                      break;
                    } else if (ch === "&") {
                      str += this.scanXHTMLEntity(quote);
                    } else {
                      str += ch;
                    }
                  }
                  return {
                    type: 8,
                    value: str,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp === 46) {
                  var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1);
                  var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2);
                  var value = n1 === 46 && n2 === 46 ? "..." : ".";
                  var start = this.scanner.index;
                  this.scanner.index += value.length;
                  return {
                    type: 7,
                    value,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                if (cp === 96) {
                  return {
                    type: 10,
                    value: "",
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start: this.scanner.index,
                    end: this.scanner.index
                  };
                }
                if (character_1.Character.isIdentifierStart(cp) && cp !== 92) {
                  var start = this.scanner.index;
                  ++this.scanner.index;
                  while (!this.scanner.eof()) {
                    var ch = this.scanner.source.charCodeAt(this.scanner.index);
                    if (character_1.Character.isIdentifierPart(ch) && ch !== 92) {
                      ++this.scanner.index;
                    } else if (ch === 45) {
                      ++this.scanner.index;
                    } else {
                      break;
                    }
                  }
                  var id = this.scanner.source.slice(start, this.scanner.index);
                  return {
                    type: 100,
                    value: id,
                    lineNumber: this.scanner.lineNumber,
                    lineStart: this.scanner.lineStart,
                    start,
                    end: this.scanner.index
                  };
                }
                return this.scanner.lex();
              };
              JSXParser2.prototype.nextJSXToken = function() {
                this.collectComments();
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var token = this.lexJSX();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                if (this.config.tokens) {
                  this.tokens.push(this.convertToken(token));
                }
                return token;
              };
              JSXParser2.prototype.nextJSXText = function() {
                this.startMarker.index = this.scanner.index;
                this.startMarker.line = this.scanner.lineNumber;
                this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                var start = this.scanner.index;
                var text = "";
                while (!this.scanner.eof()) {
                  var ch = this.scanner.source[this.scanner.index];
                  if (ch === "{" || ch === "<") {
                    break;
                  }
                  ++this.scanner.index;
                  text += ch;
                  if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.scanner.lineNumber;
                    if (ch === "\r" && this.scanner.source[this.scanner.index] === "\n") {
                      ++this.scanner.index;
                    }
                    this.scanner.lineStart = this.scanner.index;
                  }
                }
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                var token = {
                  type: 101,
                  value: text,
                  lineNumber: this.scanner.lineNumber,
                  lineStart: this.scanner.lineStart,
                  start,
                  end: this.scanner.index
                };
                if (text.length > 0 && this.config.tokens) {
                  this.tokens.push(this.convertToken(token));
                }
                return token;
              };
              JSXParser2.prototype.peekJSXToken = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.lexJSX();
                this.scanner.restoreState(state);
                return next;
              };
              JSXParser2.prototype.expectJSX = function(value) {
                var token = this.nextJSXToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              JSXParser2.prototype.matchJSX = function(value) {
                var next = this.peekJSXToken();
                return next.type === 7 && next.value === value;
              };
              JSXParser2.prototype.parseJSXIdentifier = function() {
                var node = this.createJSXNode();
                var token = this.nextJSXToken();
                if (token.type !== 100) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new JSXNode.JSXIdentifier(token.value));
              };
              JSXParser2.prototype.parseJSXElementName = function() {
                var node = this.createJSXNode();
                var elementName = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = elementName;
                  this.expectJSX(":");
                  var name_1 = this.parseJSXIdentifier();
                  elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1));
                } else if (this.matchJSX(".")) {
                  while (this.matchJSX(".")) {
                    var object = elementName;
                    this.expectJSX(".");
                    var property = this.parseJSXIdentifier();
                    elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property));
                  }
                }
                return elementName;
              };
              JSXParser2.prototype.parseJSXAttributeName = function() {
                var node = this.createJSXNode();
                var attributeName;
                var identifier = this.parseJSXIdentifier();
                if (this.matchJSX(":")) {
                  var namespace = identifier;
                  this.expectJSX(":");
                  var name_2 = this.parseJSXIdentifier();
                  attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2));
                } else {
                  attributeName = identifier;
                }
                return attributeName;
              };
              JSXParser2.prototype.parseJSXStringLiteralAttribute = function() {
                var node = this.createJSXNode();
                var token = this.nextJSXToken();
                if (token.type !== 8) {
                  this.throwUnexpectedToken(token);
                }
                var raw = this.getTokenRaw(token);
                return this.finalize(node, new Node.Literal(token.value, raw));
              };
              JSXParser2.prototype.parseJSXExpressionAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.finishJSX();
                if (this.match("}")) {
                  this.tolerateError("JSX attributes must only be assigned a non-empty expression");
                }
                var expression = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXAttributeValue = function() {
                return this.matchJSX("{") ? this.parseJSXExpressionAttribute() : this.matchJSX("<") ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute();
              };
              JSXParser2.prototype.parseJSXNameValueAttribute = function() {
                var node = this.createJSXNode();
                var name = this.parseJSXAttributeName();
                var value = null;
                if (this.matchJSX("=")) {
                  this.expectJSX("=");
                  value = this.parseJSXAttributeValue();
                }
                return this.finalize(node, new JSXNode.JSXAttribute(name, value));
              };
              JSXParser2.prototype.parseJSXSpreadAttribute = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                this.expectJSX("...");
                this.finishJSX();
                var argument = this.parseAssignmentExpression();
                this.reenterJSX();
                return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument));
              };
              JSXParser2.prototype.parseJSXAttributes = function() {
                var attributes = [];
                while (!this.matchJSX("/") && !this.matchJSX(">")) {
                  var attribute = this.matchJSX("{") ? this.parseJSXSpreadAttribute() : this.parseJSXNameValueAttribute();
                  attributes.push(attribute);
                }
                return attributes;
              };
              JSXParser2.prototype.parseJSXOpeningElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                var name = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXBoundaryElement = function() {
                var node = this.createJSXNode();
                this.expectJSX("<");
                if (this.matchJSX("/")) {
                  this.expectJSX("/");
                  var name_3 = this.parseJSXElementName();
                  this.expectJSX(">");
                  return this.finalize(node, new JSXNode.JSXClosingElement(name_3));
                }
                var name = this.parseJSXElementName();
                var attributes = this.parseJSXAttributes();
                var selfClosing = this.matchJSX("/");
                if (selfClosing) {
                  this.expectJSX("/");
                }
                this.expectJSX(">");
                return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes));
              };
              JSXParser2.prototype.parseJSXEmptyExpression = function() {
                var node = this.createJSXChildNode();
                this.collectComments();
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                return this.finalize(node, new JSXNode.JSXEmptyExpression());
              };
              JSXParser2.prototype.parseJSXExpressionContainer = function() {
                var node = this.createJSXNode();
                this.expectJSX("{");
                var expression;
                if (this.matchJSX("}")) {
                  expression = this.parseJSXEmptyExpression();
                  this.expectJSX("}");
                } else {
                  this.finishJSX();
                  expression = this.parseAssignmentExpression();
                  this.reenterJSX();
                }
                return this.finalize(node, new JSXNode.JSXExpressionContainer(expression));
              };
              JSXParser2.prototype.parseJSXChildren = function() {
                var children = [];
                while (!this.scanner.eof()) {
                  var node = this.createJSXChildNode();
                  var token = this.nextJSXText();
                  if (token.start < token.end) {
                    var raw = this.getTokenRaw(token);
                    var child = this.finalize(node, new JSXNode.JSXText(token.value, raw));
                    children.push(child);
                  }
                  if (this.scanner.source[this.scanner.index] === "{") {
                    var container = this.parseJSXExpressionContainer();
                    children.push(container);
                  } else {
                    break;
                  }
                }
                return children;
              };
              JSXParser2.prototype.parseComplexJSXElement = function(el) {
                var stack = [];
                while (!this.scanner.eof()) {
                  el.children = el.children.concat(this.parseJSXChildren());
                  var node = this.createJSXChildNode();
                  var element = this.parseJSXBoundaryElement();
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) {
                    var opening = element;
                    if (opening.selfClosing) {
                      var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null));
                      el.children.push(child);
                    } else {
                      stack.push(el);
                      el = { node, opening, closing: null, children: [] };
                    }
                  }
                  if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) {
                    el.closing = element;
                    var open_1 = getQualifiedElementName(el.opening.name);
                    var close_1 = getQualifiedElementName(el.closing.name);
                    if (open_1 !== close_1) {
                      this.tolerateError("Expected corresponding JSX closing tag for %0", open_1);
                    }
                    if (stack.length > 0) {
                      var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing));
                      el = stack[stack.length - 1];
                      el.children.push(child);
                      stack.pop();
                    } else {
                      break;
                    }
                  }
                }
                return el;
              };
              JSXParser2.prototype.parseJSXElement = function() {
                var node = this.createJSXNode();
                var opening = this.parseJSXOpeningElement();
                var children = [];
                var closing = null;
                if (!opening.selfClosing) {
                  var el = this.parseComplexJSXElement({ node, opening, closing, children });
                  children = el.children;
                  closing = el.closing;
                }
                return this.finalize(node, new JSXNode.JSXElement(opening, children, closing));
              };
              JSXParser2.prototype.parseJSXRoot = function() {
                if (this.config.tokens) {
                  this.tokens.pop();
                }
                this.startJSX();
                var element = this.parseJSXElement();
                this.finishJSX();
                return element;
              };
              JSXParser2.prototype.isStartOfExpression = function() {
                return _super.prototype.isStartOfExpression.call(this) || this.match("<");
              };
              return JSXParser2;
            }(parser_1.Parser);
            exports2.JSXParser = JSXParser;
          },
          /* 4 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var Regex = {
              // Unicode v8.0.0 NonAsciiIdentifierStart:
              NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/,
              // Unicode v8.0.0 NonAsciiIdentifierPart:
              NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/
            };
            exports2.Character = {
              /* tslint:disable:no-bitwise */
              fromCodePoint: /* @__PURE__ */ __name(function(cp) {
                return cp < 65536 ? String.fromCharCode(cp) : String.fromCharCode(55296 + (cp - 65536 >> 10)) + String.fromCharCode(56320 + (cp - 65536 & 1023));
              }, "fromCodePoint"),
              // https://tc39.github.io/ecma262/#sec-white-space
              isWhiteSpace: /* @__PURE__ */ __name(function(cp) {
                return cp === 32 || cp === 9 || cp === 11 || cp === 12 || cp === 160 || cp >= 5760 && [5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279].indexOf(cp) >= 0;
              }, "isWhiteSpace"),
              // https://tc39.github.io/ecma262/#sec-line-terminators
              isLineTerminator: /* @__PURE__ */ __name(function(cp) {
                return cp === 10 || cp === 13 || cp === 8232 || cp === 8233;
              }, "isLineTerminator"),
              // https://tc39.github.io/ecma262/#sec-names-and-keywords
              isIdentifierStart: /* @__PURE__ */ __name(function(cp) {
                return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierStart.test(exports2.Character.fromCodePoint(cp));
              }, "isIdentifierStart"),
              isIdentifierPart: /* @__PURE__ */ __name(function(cp) {
                return cp === 36 || cp === 95 || cp >= 65 && cp <= 90 || cp >= 97 && cp <= 122 || cp >= 48 && cp <= 57 || cp === 92 || cp >= 128 && Regex.NonAsciiIdentifierPart.test(exports2.Character.fromCodePoint(cp));
              }, "isIdentifierPart"),
              // https://tc39.github.io/ecma262/#sec-literals-numeric-literals
              isDecimalDigit: /* @__PURE__ */ __name(function(cp) {
                return cp >= 48 && cp <= 57;
              }, "isDecimalDigit"),
              isHexDigit: /* @__PURE__ */ __name(function(cp) {
                return cp >= 48 && cp <= 57 || cp >= 65 && cp <= 70 || cp >= 97 && cp <= 102;
              }, "isHexDigit"),
              isOctalDigit: /* @__PURE__ */ __name(function(cp) {
                return cp >= 48 && cp <= 55;
              }, "isOctalDigit")
            };
          },
          /* 5 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var jsx_syntax_1 = __webpack_require__(6);
            var JSXClosingElement = /* @__PURE__ */ function() {
              function JSXClosingElement2(name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement;
                this.name = name;
              }
              __name(JSXClosingElement2, "JSXClosingElement");
              return JSXClosingElement2;
            }();
            exports2.JSXClosingElement = JSXClosingElement;
            var JSXElement = /* @__PURE__ */ function() {
              function JSXElement2(openingElement, children, closingElement) {
                this.type = jsx_syntax_1.JSXSyntax.JSXElement;
                this.openingElement = openingElement;
                this.children = children;
                this.closingElement = closingElement;
              }
              __name(JSXElement2, "JSXElement");
              return JSXElement2;
            }();
            exports2.JSXElement = JSXElement;
            var JSXEmptyExpression = /* @__PURE__ */ function() {
              function JSXEmptyExpression2() {
                this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression;
              }
              __name(JSXEmptyExpression2, "JSXEmptyExpression");
              return JSXEmptyExpression2;
            }();
            exports2.JSXEmptyExpression = JSXEmptyExpression;
            var JSXExpressionContainer = /* @__PURE__ */ function() {
              function JSXExpressionContainer2(expression) {
                this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer;
                this.expression = expression;
              }
              __name(JSXExpressionContainer2, "JSXExpressionContainer");
              return JSXExpressionContainer2;
            }();
            exports2.JSXExpressionContainer = JSXExpressionContainer;
            var JSXIdentifier = /* @__PURE__ */ function() {
              function JSXIdentifier2(name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier;
                this.name = name;
              }
              __name(JSXIdentifier2, "JSXIdentifier");
              return JSXIdentifier2;
            }();
            exports2.JSXIdentifier = JSXIdentifier;
            var JSXMemberExpression = /* @__PURE__ */ function() {
              function JSXMemberExpression2(object, property) {
                this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression;
                this.object = object;
                this.property = property;
              }
              __name(JSXMemberExpression2, "JSXMemberExpression");
              return JSXMemberExpression2;
            }();
            exports2.JSXMemberExpression = JSXMemberExpression;
            var JSXAttribute = /* @__PURE__ */ function() {
              function JSXAttribute2(name, value) {
                this.type = jsx_syntax_1.JSXSyntax.JSXAttribute;
                this.name = name;
                this.value = value;
              }
              __name(JSXAttribute2, "JSXAttribute");
              return JSXAttribute2;
            }();
            exports2.JSXAttribute = JSXAttribute;
            var JSXNamespacedName = /* @__PURE__ */ function() {
              function JSXNamespacedName2(namespace, name) {
                this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName;
                this.namespace = namespace;
                this.name = name;
              }
              __name(JSXNamespacedName2, "JSXNamespacedName");
              return JSXNamespacedName2;
            }();
            exports2.JSXNamespacedName = JSXNamespacedName;
            var JSXOpeningElement = /* @__PURE__ */ function() {
              function JSXOpeningElement2(name, selfClosing, attributes) {
                this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement;
                this.name = name;
                this.selfClosing = selfClosing;
                this.attributes = attributes;
              }
              __name(JSXOpeningElement2, "JSXOpeningElement");
              return JSXOpeningElement2;
            }();
            exports2.JSXOpeningElement = JSXOpeningElement;
            var JSXSpreadAttribute = /* @__PURE__ */ function() {
              function JSXSpreadAttribute2(argument) {
                this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute;
                this.argument = argument;
              }
              __name(JSXSpreadAttribute2, "JSXSpreadAttribute");
              return JSXSpreadAttribute2;
            }();
            exports2.JSXSpreadAttribute = JSXSpreadAttribute;
            var JSXText = /* @__PURE__ */ function() {
              function JSXText2(value, raw) {
                this.type = jsx_syntax_1.JSXSyntax.JSXText;
                this.value = value;
                this.raw = raw;
              }
              __name(JSXText2, "JSXText");
              return JSXText2;
            }();
            exports2.JSXText = JSXText;
          },
          /* 6 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            exports2.JSXSyntax = {
              JSXAttribute: "JSXAttribute",
              JSXClosingElement: "JSXClosingElement",
              JSXElement: "JSXElement",
              JSXEmptyExpression: "JSXEmptyExpression",
              JSXExpressionContainer: "JSXExpressionContainer",
              JSXIdentifier: "JSXIdentifier",
              JSXMemberExpression: "JSXMemberExpression",
              JSXNamespacedName: "JSXNamespacedName",
              JSXOpeningElement: "JSXOpeningElement",
              JSXSpreadAttribute: "JSXSpreadAttribute",
              JSXText: "JSXText"
            };
          },
          /* 7 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var syntax_1 = __webpack_require__(2);
            var ArrayExpression = /* @__PURE__ */ function() {
              function ArrayExpression2(elements) {
                this.type = syntax_1.Syntax.ArrayExpression;
                this.elements = elements;
              }
              __name(ArrayExpression2, "ArrayExpression");
              return ArrayExpression2;
            }();
            exports2.ArrayExpression = ArrayExpression;
            var ArrayPattern = /* @__PURE__ */ function() {
              function ArrayPattern2(elements) {
                this.type = syntax_1.Syntax.ArrayPattern;
                this.elements = elements;
              }
              __name(ArrayPattern2, "ArrayPattern");
              return ArrayPattern2;
            }();
            exports2.ArrayPattern = ArrayPattern;
            var ArrowFunctionExpression = /* @__PURE__ */ function() {
              function ArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = false;
              }
              __name(ArrowFunctionExpression2, "ArrowFunctionExpression");
              return ArrowFunctionExpression2;
            }();
            exports2.ArrowFunctionExpression = ArrowFunctionExpression;
            var AssignmentExpression = /* @__PURE__ */ function() {
              function AssignmentExpression2(operator, left, right) {
                this.type = syntax_1.Syntax.AssignmentExpression;
                this.operator = operator;
                this.left = left;
                this.right = right;
              }
              __name(AssignmentExpression2, "AssignmentExpression");
              return AssignmentExpression2;
            }();
            exports2.AssignmentExpression = AssignmentExpression;
            var AssignmentPattern = /* @__PURE__ */ function() {
              function AssignmentPattern2(left, right) {
                this.type = syntax_1.Syntax.AssignmentPattern;
                this.left = left;
                this.right = right;
              }
              __name(AssignmentPattern2, "AssignmentPattern");
              return AssignmentPattern2;
            }();
            exports2.AssignmentPattern = AssignmentPattern;
            var AsyncArrowFunctionExpression = /* @__PURE__ */ function() {
              function AsyncArrowFunctionExpression2(params, body, expression) {
                this.type = syntax_1.Syntax.ArrowFunctionExpression;
                this.id = null;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = expression;
                this.async = true;
              }
              __name(AsyncArrowFunctionExpression2, "AsyncArrowFunctionExpression");
              return AsyncArrowFunctionExpression2;
            }();
            exports2.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression;
            var AsyncFunctionDeclaration = /* @__PURE__ */ function() {
              function AsyncFunctionDeclaration2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              __name(AsyncFunctionDeclaration2, "AsyncFunctionDeclaration");
              return AsyncFunctionDeclaration2;
            }();
            exports2.AsyncFunctionDeclaration = AsyncFunctionDeclaration;
            var AsyncFunctionExpression = /* @__PURE__ */ function() {
              function AsyncFunctionExpression2(id, params, body) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = false;
                this.expression = false;
                this.async = true;
              }
              __name(AsyncFunctionExpression2, "AsyncFunctionExpression");
              return AsyncFunctionExpression2;
            }();
            exports2.AsyncFunctionExpression = AsyncFunctionExpression;
            var AwaitExpression = /* @__PURE__ */ function() {
              function AwaitExpression2(argument) {
                this.type = syntax_1.Syntax.AwaitExpression;
                this.argument = argument;
              }
              __name(AwaitExpression2, "AwaitExpression");
              return AwaitExpression2;
            }();
            exports2.AwaitExpression = AwaitExpression;
            var BinaryExpression = /* @__PURE__ */ function() {
              function BinaryExpression2(operator, left, right) {
                var logical = operator === "||" || operator === "&&";
                this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression;
                this.operator = operator;
                this.left = left;
                this.right = right;
              }
              __name(BinaryExpression2, "BinaryExpression");
              return BinaryExpression2;
            }();
            exports2.BinaryExpression = BinaryExpression;
            var BlockStatement = /* @__PURE__ */ function() {
              function BlockStatement2(body) {
                this.type = syntax_1.Syntax.BlockStatement;
                this.body = body;
              }
              __name(BlockStatement2, "BlockStatement");
              return BlockStatement2;
            }();
            exports2.BlockStatement = BlockStatement;
            var BreakStatement = /* @__PURE__ */ function() {
              function BreakStatement2(label) {
                this.type = syntax_1.Syntax.BreakStatement;
                this.label = label;
              }
              __name(BreakStatement2, "BreakStatement");
              return BreakStatement2;
            }();
            exports2.BreakStatement = BreakStatement;
            var CallExpression = /* @__PURE__ */ function() {
              function CallExpression2(callee, args) {
                this.type = syntax_1.Syntax.CallExpression;
                this.callee = callee;
                this.arguments = args;
              }
              __name(CallExpression2, "CallExpression");
              return CallExpression2;
            }();
            exports2.CallExpression = CallExpression;
            var CatchClause = /* @__PURE__ */ function() {
              function CatchClause2(param, body) {
                this.type = syntax_1.Syntax.CatchClause;
                this.param = param;
                this.body = body;
              }
              __name(CatchClause2, "CatchClause");
              return CatchClause2;
            }();
            exports2.CatchClause = CatchClause;
            var ClassBody = /* @__PURE__ */ function() {
              function ClassBody2(body) {
                this.type = syntax_1.Syntax.ClassBody;
                this.body = body;
              }
              __name(ClassBody2, "ClassBody");
              return ClassBody2;
            }();
            exports2.ClassBody = ClassBody;
            var ClassDeclaration = /* @__PURE__ */ function() {
              function ClassDeclaration2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassDeclaration;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              __name(ClassDeclaration2, "ClassDeclaration");
              return ClassDeclaration2;
            }();
            exports2.ClassDeclaration = ClassDeclaration;
            var ClassExpression = /* @__PURE__ */ function() {
              function ClassExpression2(id, superClass, body) {
                this.type = syntax_1.Syntax.ClassExpression;
                this.id = id;
                this.superClass = superClass;
                this.body = body;
              }
              __name(ClassExpression2, "ClassExpression");
              return ClassExpression2;
            }();
            exports2.ClassExpression = ClassExpression;
            var ComputedMemberExpression = /* @__PURE__ */ function() {
              function ComputedMemberExpression2(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = true;
                this.object = object;
                this.property = property;
              }
              __name(ComputedMemberExpression2, "ComputedMemberExpression");
              return ComputedMemberExpression2;
            }();
            exports2.ComputedMemberExpression = ComputedMemberExpression;
            var ConditionalExpression = /* @__PURE__ */ function() {
              function ConditionalExpression2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.ConditionalExpression;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              __name(ConditionalExpression2, "ConditionalExpression");
              return ConditionalExpression2;
            }();
            exports2.ConditionalExpression = ConditionalExpression;
            var ContinueStatement = /* @__PURE__ */ function() {
              function ContinueStatement2(label) {
                this.type = syntax_1.Syntax.ContinueStatement;
                this.label = label;
              }
              __name(ContinueStatement2, "ContinueStatement");
              return ContinueStatement2;
            }();
            exports2.ContinueStatement = ContinueStatement;
            var DebuggerStatement = /* @__PURE__ */ function() {
              function DebuggerStatement2() {
                this.type = syntax_1.Syntax.DebuggerStatement;
              }
              __name(DebuggerStatement2, "DebuggerStatement");
              return DebuggerStatement2;
            }();
            exports2.DebuggerStatement = DebuggerStatement;
            var Directive = /* @__PURE__ */ function() {
              function Directive2(expression, directive) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
                this.directive = directive;
              }
              __name(Directive2, "Directive");
              return Directive2;
            }();
            exports2.Directive = Directive;
            var DoWhileStatement = /* @__PURE__ */ function() {
              function DoWhileStatement2(body, test) {
                this.type = syntax_1.Syntax.DoWhileStatement;
                this.body = body;
                this.test = test;
              }
              __name(DoWhileStatement2, "DoWhileStatement");
              return DoWhileStatement2;
            }();
            exports2.DoWhileStatement = DoWhileStatement;
            var EmptyStatement = /* @__PURE__ */ function() {
              function EmptyStatement2() {
                this.type = syntax_1.Syntax.EmptyStatement;
              }
              __name(EmptyStatement2, "EmptyStatement");
              return EmptyStatement2;
            }();
            exports2.EmptyStatement = EmptyStatement;
            var ExportAllDeclaration = /* @__PURE__ */ function() {
              function ExportAllDeclaration2(source) {
                this.type = syntax_1.Syntax.ExportAllDeclaration;
                this.source = source;
              }
              __name(ExportAllDeclaration2, "ExportAllDeclaration");
              return ExportAllDeclaration2;
            }();
            exports2.ExportAllDeclaration = ExportAllDeclaration;
            var ExportDefaultDeclaration = /* @__PURE__ */ function() {
              function ExportDefaultDeclaration2(declaration) {
                this.type = syntax_1.Syntax.ExportDefaultDeclaration;
                this.declaration = declaration;
              }
              __name(ExportDefaultDeclaration2, "ExportDefaultDeclaration");
              return ExportDefaultDeclaration2;
            }();
            exports2.ExportDefaultDeclaration = ExportDefaultDeclaration;
            var ExportNamedDeclaration = /* @__PURE__ */ function() {
              function ExportNamedDeclaration2(declaration, specifiers, source) {
                this.type = syntax_1.Syntax.ExportNamedDeclaration;
                this.declaration = declaration;
                this.specifiers = specifiers;
                this.source = source;
              }
              __name(ExportNamedDeclaration2, "ExportNamedDeclaration");
              return ExportNamedDeclaration2;
            }();
            exports2.ExportNamedDeclaration = ExportNamedDeclaration;
            var ExportSpecifier = /* @__PURE__ */ function() {
              function ExportSpecifier2(local, exported) {
                this.type = syntax_1.Syntax.ExportSpecifier;
                this.exported = exported;
                this.local = local;
              }
              __name(ExportSpecifier2, "ExportSpecifier");
              return ExportSpecifier2;
            }();
            exports2.ExportSpecifier = ExportSpecifier;
            var ExpressionStatement = /* @__PURE__ */ function() {
              function ExpressionStatement2(expression) {
                this.type = syntax_1.Syntax.ExpressionStatement;
                this.expression = expression;
              }
              __name(ExpressionStatement2, "ExpressionStatement");
              return ExpressionStatement2;
            }();
            exports2.ExpressionStatement = ExpressionStatement;
            var ForInStatement = /* @__PURE__ */ function() {
              function ForInStatement2(left, right, body) {
                this.type = syntax_1.Syntax.ForInStatement;
                this.left = left;
                this.right = right;
                this.body = body;
                this.each = false;
              }
              __name(ForInStatement2, "ForInStatement");
              return ForInStatement2;
            }();
            exports2.ForInStatement = ForInStatement;
            var ForOfStatement = /* @__PURE__ */ function() {
              function ForOfStatement2(left, right, body) {
                this.type = syntax_1.Syntax.ForOfStatement;
                this.left = left;
                this.right = right;
                this.body = body;
              }
              __name(ForOfStatement2, "ForOfStatement");
              return ForOfStatement2;
            }();
            exports2.ForOfStatement = ForOfStatement;
            var ForStatement = /* @__PURE__ */ function() {
              function ForStatement2(init, test, update, body) {
                this.type = syntax_1.Syntax.ForStatement;
                this.init = init;
                this.test = test;
                this.update = update;
                this.body = body;
              }
              __name(ForStatement2, "ForStatement");
              return ForStatement2;
            }();
            exports2.ForStatement = ForStatement;
            var FunctionDeclaration = /* @__PURE__ */ function() {
              function FunctionDeclaration2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionDeclaration;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              __name(FunctionDeclaration2, "FunctionDeclaration");
              return FunctionDeclaration2;
            }();
            exports2.FunctionDeclaration = FunctionDeclaration;
            var FunctionExpression = /* @__PURE__ */ function() {
              function FunctionExpression2(id, params, body, generator) {
                this.type = syntax_1.Syntax.FunctionExpression;
                this.id = id;
                this.params = params;
                this.body = body;
                this.generator = generator;
                this.expression = false;
                this.async = false;
              }
              __name(FunctionExpression2, "FunctionExpression");
              return FunctionExpression2;
            }();
            exports2.FunctionExpression = FunctionExpression;
            var Identifier = /* @__PURE__ */ function() {
              function Identifier2(name) {
                this.type = syntax_1.Syntax.Identifier;
                this.name = name;
              }
              __name(Identifier2, "Identifier");
              return Identifier2;
            }();
            exports2.Identifier = Identifier;
            var IfStatement = /* @__PURE__ */ function() {
              function IfStatement2(test, consequent, alternate) {
                this.type = syntax_1.Syntax.IfStatement;
                this.test = test;
                this.consequent = consequent;
                this.alternate = alternate;
              }
              __name(IfStatement2, "IfStatement");
              return IfStatement2;
            }();
            exports2.IfStatement = IfStatement;
            var ImportDeclaration = /* @__PURE__ */ function() {
              function ImportDeclaration2(specifiers, source) {
                this.type = syntax_1.Syntax.ImportDeclaration;
                this.specifiers = specifiers;
                this.source = source;
              }
              __name(ImportDeclaration2, "ImportDeclaration");
              return ImportDeclaration2;
            }();
            exports2.ImportDeclaration = ImportDeclaration;
            var ImportDefaultSpecifier = /* @__PURE__ */ function() {
              function ImportDefaultSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportDefaultSpecifier;
                this.local = local;
              }
              __name(ImportDefaultSpecifier2, "ImportDefaultSpecifier");
              return ImportDefaultSpecifier2;
            }();
            exports2.ImportDefaultSpecifier = ImportDefaultSpecifier;
            var ImportNamespaceSpecifier = /* @__PURE__ */ function() {
              function ImportNamespaceSpecifier2(local) {
                this.type = syntax_1.Syntax.ImportNamespaceSpecifier;
                this.local = local;
              }
              __name(ImportNamespaceSpecifier2, "ImportNamespaceSpecifier");
              return ImportNamespaceSpecifier2;
            }();
            exports2.ImportNamespaceSpecifier = ImportNamespaceSpecifier;
            var ImportSpecifier = /* @__PURE__ */ function() {
              function ImportSpecifier2(local, imported) {
                this.type = syntax_1.Syntax.ImportSpecifier;
                this.local = local;
                this.imported = imported;
              }
              __name(ImportSpecifier2, "ImportSpecifier");
              return ImportSpecifier2;
            }();
            exports2.ImportSpecifier = ImportSpecifier;
            var LabeledStatement = /* @__PURE__ */ function() {
              function LabeledStatement2(label, body) {
                this.type = syntax_1.Syntax.LabeledStatement;
                this.label = label;
                this.body = body;
              }
              __name(LabeledStatement2, "LabeledStatement");
              return LabeledStatement2;
            }();
            exports2.LabeledStatement = LabeledStatement;
            var Literal = /* @__PURE__ */ function() {
              function Literal2(value, raw) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw;
              }
              __name(Literal2, "Literal");
              return Literal2;
            }();
            exports2.Literal = Literal;
            var MetaProperty = /* @__PURE__ */ function() {
              function MetaProperty2(meta, property) {
                this.type = syntax_1.Syntax.MetaProperty;
                this.meta = meta;
                this.property = property;
              }
              __name(MetaProperty2, "MetaProperty");
              return MetaProperty2;
            }();
            exports2.MetaProperty = MetaProperty;
            var MethodDefinition = /* @__PURE__ */ function() {
              function MethodDefinition2(key, computed, value, kind, isStatic) {
                this.type = syntax_1.Syntax.MethodDefinition;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.static = isStatic;
              }
              __name(MethodDefinition2, "MethodDefinition");
              return MethodDefinition2;
            }();
            exports2.MethodDefinition = MethodDefinition;
            var Module = /* @__PURE__ */ function() {
              function Module2(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "module";
              }
              __name(Module2, "Module");
              return Module2;
            }();
            exports2.Module = Module;
            var NewExpression = /* @__PURE__ */ function() {
              function NewExpression2(callee, args) {
                this.type = syntax_1.Syntax.NewExpression;
                this.callee = callee;
                this.arguments = args;
              }
              __name(NewExpression2, "NewExpression");
              return NewExpression2;
            }();
            exports2.NewExpression = NewExpression;
            var ObjectExpression = /* @__PURE__ */ function() {
              function ObjectExpression2(properties) {
                this.type = syntax_1.Syntax.ObjectExpression;
                this.properties = properties;
              }
              __name(ObjectExpression2, "ObjectExpression");
              return ObjectExpression2;
            }();
            exports2.ObjectExpression = ObjectExpression;
            var ObjectPattern = /* @__PURE__ */ function() {
              function ObjectPattern2(properties) {
                this.type = syntax_1.Syntax.ObjectPattern;
                this.properties = properties;
              }
              __name(ObjectPattern2, "ObjectPattern");
              return ObjectPattern2;
            }();
            exports2.ObjectPattern = ObjectPattern;
            var Property = /* @__PURE__ */ function() {
              function Property2(kind, key, computed, value, method, shorthand) {
                this.type = syntax_1.Syntax.Property;
                this.key = key;
                this.computed = computed;
                this.value = value;
                this.kind = kind;
                this.method = method;
                this.shorthand = shorthand;
              }
              __name(Property2, "Property");
              return Property2;
            }();
            exports2.Property = Property;
            var RegexLiteral = /* @__PURE__ */ function() {
              function RegexLiteral2(value, raw, pattern, flags) {
                this.type = syntax_1.Syntax.Literal;
                this.value = value;
                this.raw = raw;
                this.regex = { pattern, flags };
              }
              __name(RegexLiteral2, "RegexLiteral");
              return RegexLiteral2;
            }();
            exports2.RegexLiteral = RegexLiteral;
            var RestElement = /* @__PURE__ */ function() {
              function RestElement2(argument) {
                this.type = syntax_1.Syntax.RestElement;
                this.argument = argument;
              }
              __name(RestElement2, "RestElement");
              return RestElement2;
            }();
            exports2.RestElement = RestElement;
            var ReturnStatement = /* @__PURE__ */ function() {
              function ReturnStatement2(argument) {
                this.type = syntax_1.Syntax.ReturnStatement;
                this.argument = argument;
              }
              __name(ReturnStatement2, "ReturnStatement");
              return ReturnStatement2;
            }();
            exports2.ReturnStatement = ReturnStatement;
            var Script = /* @__PURE__ */ function() {
              function Script2(body) {
                this.type = syntax_1.Syntax.Program;
                this.body = body;
                this.sourceType = "script";
              }
              __name(Script2, "Script");
              return Script2;
            }();
            exports2.Script = Script;
            var SequenceExpression = /* @__PURE__ */ function() {
              function SequenceExpression2(expressions) {
                this.type = syntax_1.Syntax.SequenceExpression;
                this.expressions = expressions;
              }
              __name(SequenceExpression2, "SequenceExpression");
              return SequenceExpression2;
            }();
            exports2.SequenceExpression = SequenceExpression;
            var SpreadElement = /* @__PURE__ */ function() {
              function SpreadElement2(argument) {
                this.type = syntax_1.Syntax.SpreadElement;
                this.argument = argument;
              }
              __name(SpreadElement2, "SpreadElement");
              return SpreadElement2;
            }();
            exports2.SpreadElement = SpreadElement;
            var StaticMemberExpression = /* @__PURE__ */ function() {
              function StaticMemberExpression2(object, property) {
                this.type = syntax_1.Syntax.MemberExpression;
                this.computed = false;
                this.object = object;
                this.property = property;
              }
              __name(StaticMemberExpression2, "StaticMemberExpression");
              return StaticMemberExpression2;
            }();
            exports2.StaticMemberExpression = StaticMemberExpression;
            var Super = /* @__PURE__ */ function() {
              function Super2() {
                this.type = syntax_1.Syntax.Super;
              }
              __name(Super2, "Super");
              return Super2;
            }();
            exports2.Super = Super;
            var SwitchCase = /* @__PURE__ */ function() {
              function SwitchCase2(test, consequent) {
                this.type = syntax_1.Syntax.SwitchCase;
                this.test = test;
                this.consequent = consequent;
              }
              __name(SwitchCase2, "SwitchCase");
              return SwitchCase2;
            }();
            exports2.SwitchCase = SwitchCase;
            var SwitchStatement = /* @__PURE__ */ function() {
              function SwitchStatement2(discriminant, cases) {
                this.type = syntax_1.Syntax.SwitchStatement;
                this.discriminant = discriminant;
                this.cases = cases;
              }
              __name(SwitchStatement2, "SwitchStatement");
              return SwitchStatement2;
            }();
            exports2.SwitchStatement = SwitchStatement;
            var TaggedTemplateExpression = /* @__PURE__ */ function() {
              function TaggedTemplateExpression2(tag, quasi) {
                this.type = syntax_1.Syntax.TaggedTemplateExpression;
                this.tag = tag;
                this.quasi = quasi;
              }
              __name(TaggedTemplateExpression2, "TaggedTemplateExpression");
              return TaggedTemplateExpression2;
            }();
            exports2.TaggedTemplateExpression = TaggedTemplateExpression;
            var TemplateElement = /* @__PURE__ */ function() {
              function TemplateElement2(value, tail) {
                this.type = syntax_1.Syntax.TemplateElement;
                this.value = value;
                this.tail = tail;
              }
              __name(TemplateElement2, "TemplateElement");
              return TemplateElement2;
            }();
            exports2.TemplateElement = TemplateElement;
            var TemplateLiteral = /* @__PURE__ */ function() {
              function TemplateLiteral2(quasis, expressions) {
                this.type = syntax_1.Syntax.TemplateLiteral;
                this.quasis = quasis;
                this.expressions = expressions;
              }
              __name(TemplateLiteral2, "TemplateLiteral");
              return TemplateLiteral2;
            }();
            exports2.TemplateLiteral = TemplateLiteral;
            var ThisExpression = /* @__PURE__ */ function() {
              function ThisExpression2() {
                this.type = syntax_1.Syntax.ThisExpression;
              }
              __name(ThisExpression2, "ThisExpression");
              return ThisExpression2;
            }();
            exports2.ThisExpression = ThisExpression;
            var ThrowStatement = /* @__PURE__ */ function() {
              function ThrowStatement2(argument) {
                this.type = syntax_1.Syntax.ThrowStatement;
                this.argument = argument;
              }
              __name(ThrowStatement2, "ThrowStatement");
              return ThrowStatement2;
            }();
            exports2.ThrowStatement = ThrowStatement;
            var TryStatement = /* @__PURE__ */ function() {
              function TryStatement2(block, handler, finalizer) {
                this.type = syntax_1.Syntax.TryStatement;
                this.block = block;
                this.handler = handler;
                this.finalizer = finalizer;
              }
              __name(TryStatement2, "TryStatement");
              return TryStatement2;
            }();
            exports2.TryStatement = TryStatement;
            var UnaryExpression = /* @__PURE__ */ function() {
              function UnaryExpression2(operator, argument) {
                this.type = syntax_1.Syntax.UnaryExpression;
                this.operator = operator;
                this.argument = argument;
                this.prefix = true;
              }
              __name(UnaryExpression2, "UnaryExpression");
              return UnaryExpression2;
            }();
            exports2.UnaryExpression = UnaryExpression;
            var UpdateExpression = /* @__PURE__ */ function() {
              function UpdateExpression2(operator, argument, prefix) {
                this.type = syntax_1.Syntax.UpdateExpression;
                this.operator = operator;
                this.argument = argument;
                this.prefix = prefix;
              }
              __name(UpdateExpression2, "UpdateExpression");
              return UpdateExpression2;
            }();
            exports2.UpdateExpression = UpdateExpression;
            var VariableDeclaration = /* @__PURE__ */ function() {
              function VariableDeclaration2(declarations, kind) {
                this.type = syntax_1.Syntax.VariableDeclaration;
                this.declarations = declarations;
                this.kind = kind;
              }
              __name(VariableDeclaration2, "VariableDeclaration");
              return VariableDeclaration2;
            }();
            exports2.VariableDeclaration = VariableDeclaration;
            var VariableDeclarator = /* @__PURE__ */ function() {
              function VariableDeclarator2(id, init) {
                this.type = syntax_1.Syntax.VariableDeclarator;
                this.id = id;
                this.init = init;
              }
              __name(VariableDeclarator2, "VariableDeclarator");
              return VariableDeclarator2;
            }();
            exports2.VariableDeclarator = VariableDeclarator;
            var WhileStatement = /* @__PURE__ */ function() {
              function WhileStatement2(test, body) {
                this.type = syntax_1.Syntax.WhileStatement;
                this.test = test;
                this.body = body;
              }
              __name(WhileStatement2, "WhileStatement");
              return WhileStatement2;
            }();
            exports2.WhileStatement = WhileStatement;
            var WithStatement = /* @__PURE__ */ function() {
              function WithStatement2(object, body) {
                this.type = syntax_1.Syntax.WithStatement;
                this.object = object;
                this.body = body;
              }
              __name(WithStatement2, "WithStatement");
              return WithStatement2;
            }();
            exports2.WithStatement = WithStatement;
            var YieldExpression = /* @__PURE__ */ function() {
              function YieldExpression2(argument, delegate) {
                this.type = syntax_1.Syntax.YieldExpression;
                this.argument = argument;
                this.delegate = delegate;
              }
              __name(YieldExpression2, "YieldExpression");
              return YieldExpression2;
            }();
            exports2.YieldExpression = YieldExpression;
          },
          /* 8 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var error_handler_1 = __webpack_require__(10);
            var messages_1 = __webpack_require__(11);
            var Node = __webpack_require__(7);
            var scanner_1 = __webpack_require__(12);
            var syntax_1 = __webpack_require__(2);
            var token_1 = __webpack_require__(13);
            var ArrowParameterPlaceHolder = "ArrowParameterPlaceHolder";
            var Parser = function() {
              function Parser2(code, options, delegate) {
                if (options === void 0) {
                  options = {};
                }
                this.config = {
                  range: typeof options.range === "boolean" && options.range,
                  loc: typeof options.loc === "boolean" && options.loc,
                  source: null,
                  tokens: typeof options.tokens === "boolean" && options.tokens,
                  comment: typeof options.comment === "boolean" && options.comment,
                  tolerant: typeof options.tolerant === "boolean" && options.tolerant
                };
                if (this.config.loc && options.source && options.source !== null) {
                  this.config.source = String(options.source);
                }
                this.delegate = delegate;
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = this.config.tolerant;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = this.config.comment;
                this.operatorPrecedence = {
                  ")": 0,
                  ";": 0,
                  ",": 0,
                  "=": 0,
                  "]": 0,
                  "||": 1,
                  "&&": 2,
                  "|": 3,
                  "^": 4,
                  "&": 5,
                  "==": 6,
                  "!=": 6,
                  "===": 6,
                  "!==": 6,
                  "<": 7,
                  ">": 7,
                  "<=": 7,
                  ">=": 7,
                  "<<": 8,
                  ">>": 8,
                  ">>>": 8,
                  "+": 9,
                  "-": 9,
                  "*": 11,
                  "/": 11,
                  "%": 11
                };
                this.lookahead = {
                  type: 2,
                  value: "",
                  lineNumber: this.scanner.lineNumber,
                  lineStart: 0,
                  start: 0,
                  end: 0
                };
                this.hasLineTerminator = false;
                this.context = {
                  isModule: false,
                  await: false,
                  allowIn: true,
                  allowStrictDirective: true,
                  allowYield: true,
                  firstCoverInitializedNameError: null,
                  isAssignmentTarget: false,
                  isBindingElement: false,
                  inFunctionBody: false,
                  inIteration: false,
                  inSwitch: false,
                  labelSet: {},
                  strict: false
                };
                this.tokens = [];
                this.startMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.lastMarker = {
                  index: 0,
                  line: this.scanner.lineNumber,
                  column: 0
                };
                this.nextToken();
                this.lastMarker = {
                  index: this.scanner.index,
                  line: this.scanner.lineNumber,
                  column: this.scanner.index - this.scanner.lineStart
                };
              }
              __name(Parser2, "Parser");
              Parser2.prototype.throwError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.lastMarker.line;
                var column = this.lastMarker.column + 1;
                throw this.errorHandler.createError(index, line, column, msg);
              };
              Parser2.prototype.tolerateError = function(messageFormat) {
                var values = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                  values[_i - 1] = arguments[_i];
                }
                var args = Array.prototype.slice.call(arguments, 1);
                var msg = messageFormat.replace(/%(\d)/g, function(whole, idx) {
                  assert_1.assert(idx < args.length, "Message reference must be in range");
                  return args[idx];
                });
                var index = this.lastMarker.index;
                var line = this.scanner.lineNumber;
                var column = this.lastMarker.column + 1;
                this.errorHandler.tolerateError(index, line, column, msg);
              };
              Parser2.prototype.unexpectedTokenError = function(token, message) {
                var msg = message || messages_1.Messages.UnexpectedToken;
                var value;
                if (token) {
                  if (!message) {
                    msg = token.type === 2 ? messages_1.Messages.UnexpectedEOS : token.type === 3 ? messages_1.Messages.UnexpectedIdentifier : token.type === 6 ? messages_1.Messages.UnexpectedNumber : token.type === 8 ? messages_1.Messages.UnexpectedString : token.type === 10 ? messages_1.Messages.UnexpectedTemplate : messages_1.Messages.UnexpectedToken;
                    if (token.type === 4) {
                      if (this.scanner.isFutureReservedWord(token.value)) {
                        msg = messages_1.Messages.UnexpectedReserved;
                      } else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) {
                        msg = messages_1.Messages.StrictReservedWord;
                      }
                    }
                  }
                  value = token.value;
                } else {
                  value = "ILLEGAL";
                }
                msg = msg.replace("%0", value);
                if (token && typeof token.lineNumber === "number") {
                  var index = token.start;
                  var line = token.lineNumber;
                  var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column;
                  var column = token.start - lastMarkerLineStart + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                } else {
                  var index = this.lastMarker.index;
                  var line = this.lastMarker.line;
                  var column = this.lastMarker.column + 1;
                  return this.errorHandler.createError(index, line, column, msg);
                }
              };
              Parser2.prototype.throwUnexpectedToken = function(token, message) {
                throw this.unexpectedTokenError(token, message);
              };
              Parser2.prototype.tolerateUnexpectedToken = function(token, message) {
                this.errorHandler.tolerate(this.unexpectedTokenError(token, message));
              };
              Parser2.prototype.collectComments = function() {
                if (!this.config.comment) {
                  this.scanner.scanComments();
                } else {
                  var comments = this.scanner.scanComments();
                  if (comments.length > 0 && this.delegate) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e = comments[i];
                      var node = void 0;
                      node = {
                        type: e.multiLine ? "BlockComment" : "LineComment",
                        value: this.scanner.source.slice(e.slice[0], e.slice[1])
                      };
                      if (this.config.range) {
                        node.range = e.range;
                      }
                      if (this.config.loc) {
                        node.loc = e.loc;
                      }
                      var metadata = {
                        start: {
                          line: e.loc.start.line,
                          column: e.loc.start.column,
                          offset: e.range[0]
                        },
                        end: {
                          line: e.loc.end.line,
                          column: e.loc.end.column,
                          offset: e.range[1]
                        }
                      };
                      this.delegate(node, metadata);
                    }
                  }
                }
              };
              Parser2.prototype.getTokenRaw = function(token) {
                return this.scanner.source.slice(token.start, token.end);
              };
              Parser2.prototype.convertToken = function(token) {
                var t2 = {
                  type: token_1.TokenName[token.type],
                  value: this.getTokenRaw(token)
                };
                if (this.config.range) {
                  t2.range = [token.start, token.end];
                }
                if (this.config.loc) {
                  t2.loc = {
                    start: {
                      line: this.startMarker.line,
                      column: this.startMarker.column
                    },
                    end: {
                      line: this.scanner.lineNumber,
                      column: this.scanner.index - this.scanner.lineStart
                    }
                  };
                }
                if (token.type === 9) {
                  var pattern = token.pattern;
                  var flags = token.flags;
                  t2.regex = { pattern, flags };
                }
                return t2;
              };
              Parser2.prototype.nextToken = function() {
                var token = this.lookahead;
                this.lastMarker.index = this.scanner.index;
                this.lastMarker.line = this.scanner.lineNumber;
                this.lastMarker.column = this.scanner.index - this.scanner.lineStart;
                this.collectComments();
                if (this.scanner.index !== this.startMarker.index) {
                  this.startMarker.index = this.scanner.index;
                  this.startMarker.line = this.scanner.lineNumber;
                  this.startMarker.column = this.scanner.index - this.scanner.lineStart;
                }
                var next = this.scanner.lex();
                this.hasLineTerminator = token.lineNumber !== next.lineNumber;
                if (next && this.context.strict && next.type === 3) {
                  if (this.scanner.isStrictModeReservedWord(next.value)) {
                    next.type = 4;
                  }
                }
                this.lookahead = next;
                if (this.config.tokens && next.type !== 2) {
                  this.tokens.push(this.convertToken(next));
                }
                return token;
              };
              Parser2.prototype.nextRegexToken = function() {
                this.collectComments();
                var token = this.scanner.scanRegExp();
                if (this.config.tokens) {
                  this.tokens.pop();
                  this.tokens.push(this.convertToken(token));
                }
                this.lookahead = token;
                this.nextToken();
                return token;
              };
              Parser2.prototype.createNode = function() {
                return {
                  index: this.startMarker.index,
                  line: this.startMarker.line,
                  column: this.startMarker.column
                };
              };
              Parser2.prototype.startNode = function(token, lastLineStart) {
                if (lastLineStart === void 0) {
                  lastLineStart = 0;
                }
                var column = token.start - token.lineStart;
                var line = token.lineNumber;
                if (column < 0) {
                  column += lastLineStart;
                  line--;
                }
                return {
                  index: token.start,
                  line,
                  column
                };
              };
              Parser2.prototype.finalize = function(marker, node) {
                if (this.config.range) {
                  node.range = [marker.index, this.lastMarker.index];
                }
                if (this.config.loc) {
                  node.loc = {
                    start: {
                      line: marker.line,
                      column: marker.column
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column
                    }
                  };
                  if (this.config.source) {
                    node.loc.source = this.config.source;
                  }
                }
                if (this.delegate) {
                  var metadata = {
                    start: {
                      line: marker.line,
                      column: marker.column,
                      offset: marker.index
                    },
                    end: {
                      line: this.lastMarker.line,
                      column: this.lastMarker.column,
                      offset: this.lastMarker.index
                    }
                  };
                  this.delegate(node, metadata);
                }
                return node;
              };
              Parser2.prototype.expect = function(value) {
                var token = this.nextToken();
                if (token.type !== 7 || token.value !== value) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser2.prototype.expectCommaSeparator = function() {
                if (this.config.tolerant) {
                  var token = this.lookahead;
                  if (token.type === 7 && token.value === ",") {
                    this.nextToken();
                  } else if (token.type === 7 && token.value === ";") {
                    this.nextToken();
                    this.tolerateUnexpectedToken(token);
                  } else {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken);
                  }
                } else {
                  this.expect(",");
                }
              };
              Parser2.prototype.expectKeyword = function(keyword) {
                var token = this.nextToken();
                if (token.type !== 4 || token.value !== keyword) {
                  this.throwUnexpectedToken(token);
                }
              };
              Parser2.prototype.match = function(value) {
                return this.lookahead.type === 7 && this.lookahead.value === value;
              };
              Parser2.prototype.matchKeyword = function(keyword) {
                return this.lookahead.type === 4 && this.lookahead.value === keyword;
              };
              Parser2.prototype.matchContextualKeyword = function(keyword) {
                return this.lookahead.type === 3 && this.lookahead.value === keyword;
              };
              Parser2.prototype.matchAssign = function() {
                if (this.lookahead.type !== 7) {
                  return false;
                }
                var op = this.lookahead.value;
                return op === "=" || op === "*=" || op === "**=" || op === "/=" || op === "%=" || op === "+=" || op === "-=" || op === "<<=" || op === ">>=" || op === ">>>=" || op === "&=" || op === "^=" || op === "|=";
              };
              Parser2.prototype.isolateCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                if (this.context.firstCoverInitializedNameError !== null) {
                  this.throwUnexpectedToken(this.context.firstCoverInitializedNameError);
                }
                this.context.isBindingElement = previousIsBindingElement;
                this.context.isAssignmentTarget = previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError;
                return result;
              };
              Parser2.prototype.inheritCoverGrammar = function(parseFunction) {
                var previousIsBindingElement = this.context.isBindingElement;
                var previousIsAssignmentTarget = this.context.isAssignmentTarget;
                var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError;
                this.context.isBindingElement = true;
                this.context.isAssignmentTarget = true;
                this.context.firstCoverInitializedNameError = null;
                var result = parseFunction.call(this);
                this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement;
                this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget;
                this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError;
                return result;
              };
              Parser2.prototype.consumeSemicolon = function() {
                if (this.match(";")) {
                  this.nextToken();
                } else if (!this.hasLineTerminator) {
                  if (this.lookahead.type !== 2 && !this.match("}")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.lastMarker.index = this.startMarker.index;
                  this.lastMarker.line = this.startMarker.line;
                  this.lastMarker.column = this.startMarker.column;
                }
              };
              Parser2.prototype.parsePrimaryExpression = function() {
                var node = this.createNode();
                var expr;
                var token, raw;
                switch (this.lookahead.type) {
                  case 3:
                    if ((this.context.isModule || this.context.await) && this.lookahead.value === "await") {
                      this.tolerateUnexpectedToken(this.lookahead);
                    }
                    expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value));
                    break;
                  case 6:
                  case 8:
                    if (this.context.strict && this.lookahead.octal) {
                      this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral);
                    }
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(token.value, raw));
                    break;
                  case 1:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(token.value === "true", raw));
                    break;
                  case 5:
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    token = this.nextToken();
                    raw = this.getTokenRaw(token);
                    expr = this.finalize(node, new Node.Literal(null, raw));
                    break;
                  case 10:
                    expr = this.parseTemplateLiteral();
                    break;
                  case 7:
                    switch (this.lookahead.value) {
                      case "(":
                        this.context.isBindingElement = false;
                        expr = this.inheritCoverGrammar(this.parseGroupExpression);
                        break;
                      case "[":
                        expr = this.inheritCoverGrammar(this.parseArrayInitializer);
                        break;
                      case "{":
                        expr = this.inheritCoverGrammar(this.parseObjectInitializer);
                        break;
                      case "/":
                      case "/=":
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                        this.scanner.index = this.startMarker.index;
                        token = this.nextRegexToken();
                        raw = this.getTokenRaw(token);
                        expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags));
                        break;
                      default:
                        expr = this.throwUnexpectedToken(this.nextToken());
                    }
                    break;
                  case 4:
                    if (!this.context.strict && this.context.allowYield && this.matchKeyword("yield")) {
                      expr = this.parseIdentifierName();
                    } else if (!this.context.strict && this.matchKeyword("let")) {
                      expr = this.finalize(node, new Node.Identifier(this.nextToken().value));
                    } else {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      if (this.matchKeyword("function")) {
                        expr = this.parseFunctionExpression();
                      } else if (this.matchKeyword("this")) {
                        this.nextToken();
                        expr = this.finalize(node, new Node.ThisExpression());
                      } else if (this.matchKeyword("class")) {
                        expr = this.parseClassExpression();
                      } else {
                        expr = this.throwUnexpectedToken(this.nextToken());
                      }
                    }
                    break;
                  default:
                    expr = this.throwUnexpectedToken(this.nextToken());
                }
                return expr;
              };
              Parser2.prototype.parseSpreadElement = function() {
                var node = this.createNode();
                this.expect("...");
                var arg = this.inheritCoverGrammar(this.parseAssignmentExpression);
                return this.finalize(node, new Node.SpreadElement(arg));
              };
              Parser2.prototype.parseArrayInitializer = function() {
                var node = this.createNode();
                var elements = [];
                this.expect("[");
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else if (this.match("...")) {
                    var element = this.parseSpreadElement();
                    if (!this.match("]")) {
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      this.expect(",");
                    }
                    elements.push(element);
                  } else {
                    elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node.ArrayExpression(elements));
              };
              Parser2.prototype.parsePropertyMethod = function(params) {
                this.context.isAssignmentTarget = false;
                this.context.isBindingElement = false;
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = params.simple;
                var body = this.isolateCoverGrammar(this.parseFunctionSourceElements);
                if (this.context.strict && params.firstRestricted) {
                  this.tolerateUnexpectedToken(params.firstRestricted, params.message);
                }
                if (this.context.strict && params.stricted) {
                  this.tolerateUnexpectedToken(params.stricted, params.message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                return body;
              };
              Parser2.prototype.parsePropertyMethodFunction = function() {
                var isGenerator = false;
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser2.prototype.parsePropertyMethodAsyncFunction = function() {
                var node = this.createNode();
                var previousAllowYield = this.context.allowYield;
                var previousAwait = this.context.await;
                this.context.allowYield = false;
                this.context.await = true;
                var params = this.parseFormalParameters();
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                this.context.await = previousAwait;
                return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method));
              };
              Parser2.prototype.parseObjectPropertyKey = function() {
                var node = this.createNode();
                var token = this.nextToken();
                var key;
                switch (token.type) {
                  case 8:
                  case 6:
                    if (this.context.strict && token.octal) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral);
                    }
                    var raw = this.getTokenRaw(token);
                    key = this.finalize(node, new Node.Literal(token.value, raw));
                    break;
                  case 3:
                  case 1:
                  case 5:
                  case 4:
                    key = this.finalize(node, new Node.Identifier(token.value));
                    break;
                  case 7:
                    if (token.value === "[") {
                      key = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      this.expect("]");
                    } else {
                      key = this.throwUnexpectedToken(token);
                    }
                    break;
                  default:
                    key = this.throwUnexpectedToken(token);
                }
                return key;
              };
              Parser2.prototype.isPropertyKey = function(key, value) {
                return key.type === syntax_1.Syntax.Identifier && key.name === value || key.type === syntax_1.Syntax.Literal && key.value === value;
              };
              Parser2.prototype.parseObjectProperty = function(hasProto) {
                var node = this.createNode();
                var token = this.lookahead;
                var kind;
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var shorthand = false;
                var isAsync = false;
                if (token.type === 3) {
                  var id = token.value;
                  this.nextToken();
                  computed = this.match("[");
                  isAsync = !this.hasLineTerminator && id === "async" && !this.match(":") && !this.match("(") && !this.match("*") && !this.match(",");
                  key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id));
                } else if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3 && !isAsync && token.value === "get" && lookaheadPropertyKey) {
                  kind = "get";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.context.allowYield = false;
                  value = this.parseGetterMethod();
                } else if (token.type === 3 && !isAsync && token.value === "set" && lookaheadPropertyKey) {
                  kind = "set";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseSetterMethod();
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                } else {
                  if (!key) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  kind = "init";
                  if (this.match(":") && !isAsync) {
                    if (!computed && this.isPropertyKey(key, "__proto__")) {
                      if (hasProto.value) {
                        this.tolerateError(messages_1.Messages.DuplicateProtoProperty);
                      }
                      hasProto.value = true;
                    }
                    this.nextToken();
                    value = this.inheritCoverGrammar(this.parseAssignmentExpression);
                  } else if (this.match("(")) {
                    value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                    method = true;
                  } else if (token.type === 3) {
                    var id = this.finalize(node, new Node.Identifier(token.value));
                    if (this.match("=")) {
                      this.context.firstCoverInitializedNameError = this.lookahead;
                      this.nextToken();
                      shorthand = true;
                      var init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      value = this.finalize(node, new Node.AssignmentPattern(id, init));
                    } else {
                      shorthand = true;
                      value = id;
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand));
              };
              Parser2.prototype.parseObjectInitializer = function() {
                var node = this.createNode();
                this.expect("{");
                var properties = [];
                var hasProto = { value: false };
                while (!this.match("}")) {
                  properties.push(this.parseObjectProperty(hasProto));
                  if (!this.match("}")) {
                    this.expectCommaSeparator();
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node.ObjectExpression(properties));
              };
              Parser2.prototype.parseTemplateHead = function() {
                assert_1.assert(this.lookahead.head, "Template literal must start with a template head");
                var node = this.createNode();
                var token = this.nextToken();
                var raw = token.value;
                var cooked = token.cooked;
                return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser2.prototype.parseTemplateElement = function() {
                if (this.lookahead.type !== 10) {
                  this.throwUnexpectedToken();
                }
                var node = this.createNode();
                var token = this.nextToken();
                var raw = token.value;
                var cooked = token.cooked;
                return this.finalize(node, new Node.TemplateElement({ raw, cooked }, token.tail));
              };
              Parser2.prototype.parseTemplateLiteral = function() {
                var node = this.createNode();
                var expressions = [];
                var quasis = [];
                var quasi = this.parseTemplateHead();
                quasis.push(quasi);
                while (!quasi.tail) {
                  expressions.push(this.parseExpression());
                  quasi = this.parseTemplateElement();
                  quasis.push(quasi);
                }
                return this.finalize(node, new Node.TemplateLiteral(quasis, expressions));
              };
              Parser2.prototype.reinterpretExpressionAsPattern = function(expr) {
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                  case syntax_1.Syntax.MemberExpression:
                  case syntax_1.Syntax.RestElement:
                  case syntax_1.Syntax.AssignmentPattern:
                    break;
                  case syntax_1.Syntax.SpreadElement:
                    expr.type = syntax_1.Syntax.RestElement;
                    this.reinterpretExpressionAsPattern(expr.argument);
                    break;
                  case syntax_1.Syntax.ArrayExpression:
                    expr.type = syntax_1.Syntax.ArrayPattern;
                    for (var i = 0; i < expr.elements.length; i++) {
                      if (expr.elements[i] !== null) {
                        this.reinterpretExpressionAsPattern(expr.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectExpression:
                    expr.type = syntax_1.Syntax.ObjectPattern;
                    for (var i = 0; i < expr.properties.length; i++) {
                      this.reinterpretExpressionAsPattern(expr.properties[i].value);
                    }
                    break;
                  case syntax_1.Syntax.AssignmentExpression:
                    expr.type = syntax_1.Syntax.AssignmentPattern;
                    delete expr.operator;
                    this.reinterpretExpressionAsPattern(expr.left);
                    break;
                  default:
                    break;
                }
              };
              Parser2.prototype.parseGroupExpression = function() {
                var expr;
                this.expect("(");
                if (this.match(")")) {
                  this.nextToken();
                  if (!this.match("=>")) {
                    this.expect("=>");
                  }
                  expr = {
                    type: ArrowParameterPlaceHolder,
                    params: [],
                    async: false
                  };
                } else {
                  var startToken = this.lookahead;
                  var params = [];
                  if (this.match("...")) {
                    expr = this.parseRestElement(params);
                    this.expect(")");
                    if (!this.match("=>")) {
                      this.expect("=>");
                    }
                    expr = {
                      type: ArrowParameterPlaceHolder,
                      params: [expr],
                      async: false
                    };
                  } else {
                    var arrow = false;
                    this.context.isBindingElement = true;
                    expr = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    if (this.match(",")) {
                      var expressions = [];
                      this.context.isAssignmentTarget = false;
                      expressions.push(expr);
                      while (this.lookahead.type !== 2) {
                        if (!this.match(",")) {
                          break;
                        }
                        this.nextToken();
                        if (this.match(")")) {
                          this.nextToken();
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else if (this.match("...")) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          expressions.push(this.parseRestElement(params));
                          this.expect(")");
                          if (!this.match("=>")) {
                            this.expect("=>");
                          }
                          this.context.isBindingElement = false;
                          for (var i = 0; i < expressions.length; i++) {
                            this.reinterpretExpressionAsPattern(expressions[i]);
                          }
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: expressions,
                            async: false
                          };
                        } else {
                          expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression));
                        }
                        if (arrow) {
                          break;
                        }
                      }
                      if (!arrow) {
                        expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
                      }
                    }
                    if (!arrow) {
                      this.expect(")");
                      if (this.match("=>")) {
                        if (expr.type === syntax_1.Syntax.Identifier && expr.name === "yield") {
                          arrow = true;
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: [expr],
                            async: false
                          };
                        }
                        if (!arrow) {
                          if (!this.context.isBindingElement) {
                            this.throwUnexpectedToken(this.lookahead);
                          }
                          if (expr.type === syntax_1.Syntax.SequenceExpression) {
                            for (var i = 0; i < expr.expressions.length; i++) {
                              this.reinterpretExpressionAsPattern(expr.expressions[i]);
                            }
                          } else {
                            this.reinterpretExpressionAsPattern(expr);
                          }
                          var parameters = expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr];
                          expr = {
                            type: ArrowParameterPlaceHolder,
                            params: parameters,
                            async: false
                          };
                        }
                      }
                      this.context.isBindingElement = false;
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAssignmentExpression);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser2.prototype.isIdentifierName = function(token) {
                return token.type === 3 || token.type === 4 || token.type === 1 || token.type === 5;
              };
              Parser2.prototype.parseIdentifierName = function() {
                var node = this.createNode();
                var token = this.nextToken();
                if (!this.isIdentifierName(token)) {
                  this.throwUnexpectedToken(token);
                }
                return this.finalize(node, new Node.Identifier(token.value));
              };
              Parser2.prototype.parseNewExpression = function() {
                var node = this.createNode();
                var id = this.parseIdentifierName();
                assert_1.assert(id.name === "new", "New expression must start with `new`");
                var expr;
                if (this.match(".")) {
                  this.nextToken();
                  if (this.lookahead.type === 3 && this.context.inFunctionBody && this.lookahead.value === "target") {
                    var property = this.parseIdentifierName();
                    expr = new Node.MetaProperty(id, property);
                  } else {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression);
                  var args = this.match("(") ? this.parseArguments() : [];
                  expr = new Node.NewExpression(callee, args);
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return this.finalize(node, expr);
              };
              Parser2.prototype.parseAsyncArgument = function() {
                var arg = this.parseAssignmentExpression();
                this.context.firstCoverInitializedNameError = null;
                return arg;
              };
              Parser2.prototype.parseAsyncArguments = function() {
                this.expect("(");
                var args = [];
                if (!this.match(")")) {
                  while (true) {
                    var expr = this.match("...") ? this.parseSpreadElement() : this.isolateCoverGrammar(this.parseAsyncArgument);
                    args.push(expr);
                    if (this.match(")")) {
                      break;
                    }
                    this.expectCommaSeparator();
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return args;
              };
              Parser2.prototype.parseLeftHandSideExpressionAllowCall = function() {
                var startToken = this.lookahead;
                var maybeAsync = this.matchContextualKeyword("async");
                var previousAllowIn = this.context.allowIn;
                this.context.allowIn = true;
                var expr;
                if (this.matchKeyword("super") && this.context.inFunctionBody) {
                  expr = this.createNode();
                  this.nextToken();
                  expr = this.finalize(expr, new Node.Super());
                  if (!this.match("(") && !this.match(".") && !this.match("[")) {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                } else {
                  expr = this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                }
                while (true) {
                  if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property));
                  } else if (this.match("(")) {
                    var asyncArrow = maybeAsync && startToken.lineNumber === this.lookahead.lineNumber;
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = false;
                    var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments();
                    expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args));
                    if (asyncArrow && this.match("=>")) {
                      for (var i = 0; i < args.length; ++i) {
                        this.reinterpretExpressionAsPattern(args[i]);
                      }
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: args,
                        async: true
                      };
                    }
                  } else if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                this.context.allowIn = previousAllowIn;
                return expr;
              };
              Parser2.prototype.parseSuper = function() {
                var node = this.createNode();
                this.expectKeyword("super");
                if (!this.match("[") && !this.match(".")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                return this.finalize(node, new Node.Super());
              };
              Parser2.prototype.parseLeftHandSideExpression = function() {
                assert_1.assert(this.context.allowIn, "callee of new expression always allow in keyword.");
                var node = this.startNode(this.lookahead);
                var expr = this.matchKeyword("super") && this.context.inFunctionBody ? this.parseSuper() : this.inheritCoverGrammar(this.matchKeyword("new") ? this.parseNewExpression : this.parsePrimaryExpression);
                while (true) {
                  if (this.match("[")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect("[");
                    var property = this.isolateCoverGrammar(this.parseExpression);
                    this.expect("]");
                    expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property));
                  } else if (this.match(".")) {
                    this.context.isBindingElement = false;
                    this.context.isAssignmentTarget = true;
                    this.expect(".");
                    var property = this.parseIdentifierName();
                    expr = this.finalize(node, new Node.StaticMemberExpression(expr, property));
                  } else if (this.lookahead.type === 10 && this.lookahead.head) {
                    var quasi = this.parseTemplateLiteral();
                    expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi));
                  } else {
                    break;
                  }
                }
                return expr;
              };
              Parser2.prototype.parseUpdateExpression = function() {
                var expr;
                var startToken = this.lookahead;
                if (this.match("++") || this.match("--")) {
                  var node = this.startNode(startToken);
                  var token = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                    this.tolerateError(messages_1.Messages.StrictLHSPrefix);
                  }
                  if (!this.context.isAssignmentTarget) {
                    this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                  }
                  var prefix = true;
                  expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else {
                  expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                  if (!this.hasLineTerminator && this.lookahead.type === 7) {
                    if (this.match("++") || this.match("--")) {
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) {
                        this.tolerateError(messages_1.Messages.StrictLHSPostfix);
                      }
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      this.context.isAssignmentTarget = false;
                      this.context.isBindingElement = false;
                      var operator = this.nextToken().value;
                      var prefix = false;
                      expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix));
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseAwaitExpression = function() {
                var node = this.createNode();
                this.nextToken();
                var argument = this.parseUnaryExpression();
                return this.finalize(node, new Node.AwaitExpression(argument));
              };
              Parser2.prototype.parseUnaryExpression = function() {
                var expr;
                if (this.match("+") || this.match("-") || this.match("~") || this.match("!") || this.matchKeyword("delete") || this.matchKeyword("void") || this.matchKeyword("typeof")) {
                  var node = this.startNode(this.lookahead);
                  var token = this.nextToken();
                  expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                  expr = this.finalize(node, new Node.UnaryExpression(token.value, expr));
                  if (this.context.strict && expr.operator === "delete" && expr.argument.type === syntax_1.Syntax.Identifier) {
                    this.tolerateError(messages_1.Messages.StrictDelete);
                  }
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                } else if (this.context.await && this.matchContextualKeyword("await")) {
                  expr = this.parseAwaitExpression();
                } else {
                  expr = this.parseUpdateExpression();
                }
                return expr;
              };
              Parser2.prototype.parseExponentiationExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseUnaryExpression);
                if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match("**")) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var left = expr;
                  var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression("**", left, right));
                }
                return expr;
              };
              Parser2.prototype.binaryPrecedence = function(token) {
                var op = token.value;
                var precedence;
                if (token.type === 7) {
                  precedence = this.operatorPrecedence[op] || 0;
                } else if (token.type === 4) {
                  precedence = op === "instanceof" || this.context.allowIn && op === "in" ? 7 : 0;
                } else {
                  precedence = 0;
                }
                return precedence;
              };
              Parser2.prototype.parseBinaryExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseExponentiationExpression);
                var token = this.lookahead;
                var prec = this.binaryPrecedence(token);
                if (prec > 0) {
                  this.nextToken();
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                  var markers = [startToken, this.lookahead];
                  var left = expr;
                  var right = this.isolateCoverGrammar(this.parseExponentiationExpression);
                  var stack = [left, token.value, right];
                  var precedences = [prec];
                  while (true) {
                    prec = this.binaryPrecedence(this.lookahead);
                    if (prec <= 0) {
                      break;
                    }
                    while (stack.length > 2 && prec <= precedences[precedences.length - 1]) {
                      right = stack.pop();
                      var operator = stack.pop();
                      precedences.pop();
                      left = stack.pop();
                      markers.pop();
                      var node = this.startNode(markers[markers.length - 1]);
                      stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right)));
                    }
                    stack.push(this.nextToken().value);
                    precedences.push(prec);
                    markers.push(this.lookahead);
                    stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression));
                  }
                  var i = stack.length - 1;
                  expr = stack[i];
                  var lastMarker = markers.pop();
                  while (i > 1) {
                    var marker = markers.pop();
                    var lastLineStart = lastMarker && lastMarker.lineStart;
                    var node = this.startNode(marker, lastLineStart);
                    var operator = stack[i - 1];
                    expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr));
                    i -= 2;
                    lastMarker = marker;
                  }
                }
                return expr;
              };
              Parser2.prototype.parseConditionalExpression = function() {
                var startToken = this.lookahead;
                var expr = this.inheritCoverGrammar(this.parseBinaryExpression);
                if (this.match("?")) {
                  this.nextToken();
                  var previousAllowIn = this.context.allowIn;
                  this.context.allowIn = true;
                  var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowIn = previousAllowIn;
                  this.expect(":");
                  var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate));
                  this.context.isAssignmentTarget = false;
                  this.context.isBindingElement = false;
                }
                return expr;
              };
              Parser2.prototype.checkPatternParam = function(options, param) {
                switch (param.type) {
                  case syntax_1.Syntax.Identifier:
                    this.validateParam(options, param, param.name);
                    break;
                  case syntax_1.Syntax.RestElement:
                    this.checkPatternParam(options, param.argument);
                    break;
                  case syntax_1.Syntax.AssignmentPattern:
                    this.checkPatternParam(options, param.left);
                    break;
                  case syntax_1.Syntax.ArrayPattern:
                    for (var i = 0; i < param.elements.length; i++) {
                      if (param.elements[i] !== null) {
                        this.checkPatternParam(options, param.elements[i]);
                      }
                    }
                    break;
                  case syntax_1.Syntax.ObjectPattern:
                    for (var i = 0; i < param.properties.length; i++) {
                      this.checkPatternParam(options, param.properties[i].value);
                    }
                    break;
                  default:
                    break;
                }
                options.simple = options.simple && param instanceof Node.Identifier;
              };
              Parser2.prototype.reinterpretAsCoverFormalsList = function(expr) {
                var params = [expr];
                var options;
                var asyncArrow = false;
                switch (expr.type) {
                  case syntax_1.Syntax.Identifier:
                    break;
                  case ArrowParameterPlaceHolder:
                    params = expr.params;
                    asyncArrow = expr.async;
                    break;
                  default:
                    return null;
                }
                options = {
                  simple: true,
                  paramSet: {}
                };
                for (var i = 0; i < params.length; ++i) {
                  var param = params[i];
                  if (param.type === syntax_1.Syntax.AssignmentPattern) {
                    if (param.right.type === syntax_1.Syntax.YieldExpression) {
                      if (param.right.argument) {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                      param.right.type = syntax_1.Syntax.Identifier;
                      param.right.name = "yield";
                      delete param.right.argument;
                      delete param.right.delegate;
                    }
                  } else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === "await") {
                    this.throwUnexpectedToken(this.lookahead);
                  }
                  this.checkPatternParam(options, param);
                  params[i] = param;
                }
                if (this.context.strict || !this.context.allowYield) {
                  for (var i = 0; i < params.length; ++i) {
                    var param = params[i];
                    if (param.type === syntax_1.Syntax.YieldExpression) {
                      this.throwUnexpectedToken(this.lookahead);
                    }
                  }
                }
                if (options.message === messages_1.Messages.StrictParamDupe) {
                  var token = this.context.strict ? options.stricted : options.firstRestricted;
                  this.throwUnexpectedToken(token, options.message);
                }
                return {
                  simple: options.simple,
                  params,
                  stricted: options.stricted,
                  firstRestricted: options.firstRestricted,
                  message: options.message
                };
              };
              Parser2.prototype.parseAssignmentExpression = function() {
                var expr;
                if (!this.context.allowYield && this.matchKeyword("yield")) {
                  expr = this.parseYieldExpression();
                } else {
                  var startToken = this.lookahead;
                  var token = startToken;
                  expr = this.parseConditionalExpression();
                  if (token.type === 3 && token.lineNumber === this.lookahead.lineNumber && token.value === "async") {
                    if (this.lookahead.type === 3 || this.matchKeyword("yield")) {
                      var arg = this.parsePrimaryExpression();
                      this.reinterpretExpressionAsPattern(arg);
                      expr = {
                        type: ArrowParameterPlaceHolder,
                        params: [arg],
                        async: true
                      };
                    }
                  }
                  if (expr.type === ArrowParameterPlaceHolder || this.match("=>")) {
                    this.context.isAssignmentTarget = false;
                    this.context.isBindingElement = false;
                    var isAsync = expr.async;
                    var list = this.reinterpretAsCoverFormalsList(expr);
                    if (list) {
                      if (this.hasLineTerminator) {
                        this.tolerateUnexpectedToken(this.lookahead);
                      }
                      this.context.firstCoverInitializedNameError = null;
                      var previousStrict = this.context.strict;
                      var previousAllowStrictDirective = this.context.allowStrictDirective;
                      this.context.allowStrictDirective = list.simple;
                      var previousAllowYield = this.context.allowYield;
                      var previousAwait = this.context.await;
                      this.context.allowYield = true;
                      this.context.await = isAsync;
                      var node = this.startNode(startToken);
                      this.expect("=>");
                      var body = void 0;
                      if (this.match("{")) {
                        var previousAllowIn = this.context.allowIn;
                        this.context.allowIn = true;
                        body = this.parseFunctionSourceElements();
                        this.context.allowIn = previousAllowIn;
                      } else {
                        body = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      }
                      var expression = body.type !== syntax_1.Syntax.BlockStatement;
                      if (this.context.strict && list.firstRestricted) {
                        this.throwUnexpectedToken(list.firstRestricted, list.message);
                      }
                      if (this.context.strict && list.stricted) {
                        this.tolerateUnexpectedToken(list.stricted, list.message);
                      }
                      expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression));
                      this.context.strict = previousStrict;
                      this.context.allowStrictDirective = previousAllowStrictDirective;
                      this.context.allowYield = previousAllowYield;
                      this.context.await = previousAwait;
                    }
                  } else {
                    if (this.matchAssign()) {
                      if (!this.context.isAssignmentTarget) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInAssignment);
                      }
                      if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) {
                        var id = expr;
                        if (this.scanner.isRestrictedWord(id.name)) {
                          this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment);
                        }
                        if (this.scanner.isStrictModeReservedWord(id.name)) {
                          this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                        }
                      }
                      if (!this.match("=")) {
                        this.context.isAssignmentTarget = false;
                        this.context.isBindingElement = false;
                      } else {
                        this.reinterpretExpressionAsPattern(expr);
                      }
                      token = this.nextToken();
                      var operator = token.value;
                      var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
                      expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right));
                      this.context.firstCoverInitializedNameError = null;
                    }
                  }
                }
                return expr;
              };
              Parser2.prototype.parseExpression = function() {
                var startToken = this.lookahead;
                var expr = this.isolateCoverGrammar(this.parseAssignmentExpression);
                if (this.match(",")) {
                  var expressions = [];
                  expressions.push(expr);
                  while (this.lookahead.type !== 2) {
                    if (!this.match(",")) {
                      break;
                    }
                    this.nextToken();
                    expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                  }
                  expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions));
                }
                return expr;
              };
              Parser2.prototype.parseStatementListItem = function() {
                var statement;
                this.context.isAssignmentTarget = true;
                this.context.isBindingElement = true;
                if (this.lookahead.type === 4) {
                  switch (this.lookahead.value) {
                    case "export":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration);
                      }
                      statement = this.parseExportDeclaration();
                      break;
                    case "import":
                      if (!this.context.isModule) {
                        this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration);
                      }
                      statement = this.parseImportDeclaration();
                      break;
                    case "const":
                      statement = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "function":
                      statement = this.parseFunctionDeclaration();
                      break;
                    case "class":
                      statement = this.parseClassDeclaration();
                      break;
                    case "let":
                      statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement();
                      break;
                    default:
                      statement = this.parseStatement();
                      break;
                  }
                } else {
                  statement = this.parseStatement();
                }
                return statement;
              };
              Parser2.prototype.parseBlock = function() {
                var node = this.createNode();
                this.expect("{");
                var block = [];
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  block.push(this.parseStatementListItem());
                }
                this.expect("}");
                return this.finalize(node, new Node.BlockStatement(block));
              };
              Parser2.prototype.parseLexicalBinding = function(kind, options) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, kind);
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init = null;
                if (kind === "const") {
                  if (!this.matchKeyword("in") && !this.matchContextualKeyword("of")) {
                    if (this.match("=")) {
                      this.nextToken();
                      init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                    } else {
                      this.throwError(messages_1.Messages.DeclarationMissingInitializer, "const");
                    }
                  }
                } else if (!options.inFor && id.type !== syntax_1.Syntax.Identifier || this.match("=")) {
                  this.expect("=");
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                }
                return this.finalize(node, new Node.VariableDeclarator(id, init));
              };
              Parser2.prototype.parseBindingList = function(kind, options) {
                var list = [this.parseLexicalBinding(kind, options)];
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseLexicalBinding(kind, options));
                }
                return list;
              };
              Parser2.prototype.isLexicalDeclaration = function() {
                var state = this.scanner.saveState();
                this.scanner.scanComments();
                var next = this.scanner.lex();
                this.scanner.restoreState(state);
                return next.type === 3 || next.type === 7 && next.value === "[" || next.type === 7 && next.value === "{" || next.type === 4 && next.value === "let" || next.type === 4 && next.value === "yield";
              };
              Parser2.prototype.parseLexicalDeclaration = function(options) {
                var node = this.createNode();
                var kind = this.nextToken().value;
                assert_1.assert(kind === "let" || kind === "const", "Lexical declaration must be either let or const");
                var declarations = this.parseBindingList(kind, options);
                this.consumeSemicolon();
                return this.finalize(node, new Node.VariableDeclaration(declarations, kind));
              };
              Parser2.prototype.parseBindingRestElement = function(params, kind) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params, kind);
                return this.finalize(node, new Node.RestElement(arg));
              };
              Parser2.prototype.parseArrayPattern = function(params, kind) {
                var node = this.createNode();
                this.expect("[");
                var elements = [];
                while (!this.match("]")) {
                  if (this.match(",")) {
                    this.nextToken();
                    elements.push(null);
                  } else {
                    if (this.match("...")) {
                      elements.push(this.parseBindingRestElement(params, kind));
                      break;
                    } else {
                      elements.push(this.parsePatternWithDefault(params, kind));
                    }
                    if (!this.match("]")) {
                      this.expect(",");
                    }
                  }
                }
                this.expect("]");
                return this.finalize(node, new Node.ArrayPattern(elements));
              };
              Parser2.prototype.parsePropertyPattern = function(params, kind) {
                var node = this.createNode();
                var computed = false;
                var shorthand = false;
                var method = false;
                var key;
                var value;
                if (this.lookahead.type === 3) {
                  var keyToken = this.lookahead;
                  key = this.parseVariableIdentifier();
                  var init = this.finalize(node, new Node.Identifier(keyToken.value));
                  if (this.match("=")) {
                    params.push(keyToken);
                    shorthand = true;
                    this.nextToken();
                    var expr = this.parseAssignmentExpression();
                    value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr));
                  } else if (!this.match(":")) {
                    params.push(keyToken);
                    shorthand = true;
                    value = init;
                  } else {
                    this.expect(":");
                    value = this.parsePatternWithDefault(params, kind);
                  }
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  this.expect(":");
                  value = this.parsePatternWithDefault(params, kind);
                }
                return this.finalize(node, new Node.Property("init", key, computed, value, method, shorthand));
              };
              Parser2.prototype.parseObjectPattern = function(params, kind) {
                var node = this.createNode();
                var properties = [];
                this.expect("{");
                while (!this.match("}")) {
                  properties.push(this.parsePropertyPattern(params, kind));
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return this.finalize(node, new Node.ObjectPattern(properties));
              };
              Parser2.prototype.parsePattern = function(params, kind) {
                var pattern;
                if (this.match("[")) {
                  pattern = this.parseArrayPattern(params, kind);
                } else if (this.match("{")) {
                  pattern = this.parseObjectPattern(params, kind);
                } else {
                  if (this.matchKeyword("let") && (kind === "const" || kind === "let")) {
                    this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding);
                  }
                  params.push(this.lookahead);
                  pattern = this.parseVariableIdentifier(kind);
                }
                return pattern;
              };
              Parser2.prototype.parsePatternWithDefault = function(params, kind) {
                var startToken = this.lookahead;
                var pattern = this.parsePattern(params, kind);
                if (this.match("=")) {
                  this.nextToken();
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = true;
                  var right = this.isolateCoverGrammar(this.parseAssignmentExpression);
                  this.context.allowYield = previousAllowYield;
                  pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right));
                }
                return pattern;
              };
              Parser2.prototype.parseVariableIdentifier = function(kind) {
                var node = this.createNode();
                var token = this.nextToken();
                if (token.type === 4 && token.value === "yield") {
                  if (this.context.strict) {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                  } else if (!this.context.allowYield) {
                    this.throwUnexpectedToken(token);
                  }
                } else if (token.type !== 3) {
                  if (this.context.strict && token.type === 4 && this.scanner.isStrictModeReservedWord(token.value)) {
                    this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord);
                  } else {
                    if (this.context.strict || token.value !== "let" || kind !== "var") {
                      this.throwUnexpectedToken(token);
                    }
                  }
                } else if ((this.context.isModule || this.context.await) && token.type === 3 && token.value === "await") {
                  this.tolerateUnexpectedToken(token);
                }
                return this.finalize(node, new Node.Identifier(token.value));
              };
              Parser2.prototype.parseVariableDeclaration = function(options) {
                var node = this.createNode();
                var params = [];
                var id = this.parsePattern(params, "var");
                if (this.context.strict && id.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(id.name)) {
                    this.tolerateError(messages_1.Messages.StrictVarName);
                  }
                }
                var init = null;
                if (this.match("=")) {
                  this.nextToken();
                  init = this.isolateCoverGrammar(this.parseAssignmentExpression);
                } else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) {
                  this.expect("=");
                }
                return this.finalize(node, new Node.VariableDeclarator(id, init));
              };
              Parser2.prototype.parseVariableDeclarationList = function(options) {
                var opt = { inFor: options.inFor };
                var list = [];
                list.push(this.parseVariableDeclaration(opt));
                while (this.match(",")) {
                  this.nextToken();
                  list.push(this.parseVariableDeclaration(opt));
                }
                return list;
              };
              Parser2.prototype.parseVariableStatement = function() {
                var node = this.createNode();
                this.expectKeyword("var");
                var declarations = this.parseVariableDeclarationList({ inFor: false });
                this.consumeSemicolon();
                return this.finalize(node, new Node.VariableDeclaration(declarations, "var"));
              };
              Parser2.prototype.parseEmptyStatement = function() {
                var node = this.createNode();
                this.expect(";");
                return this.finalize(node, new Node.EmptyStatement());
              };
              Parser2.prototype.parseExpressionStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node.ExpressionStatement(expr));
              };
              Parser2.prototype.parseIfClause = function() {
                if (this.context.strict && this.matchKeyword("function")) {
                  this.tolerateError(messages_1.Messages.StrictFunction);
                }
                return this.parseStatement();
              };
              Parser2.prototype.parseIfStatement = function() {
                var node = this.createNode();
                var consequent;
                var alternate = null;
                this.expectKeyword("if");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  consequent = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  consequent = this.parseIfClause();
                  if (this.matchKeyword("else")) {
                    this.nextToken();
                    alternate = this.parseIfClause();
                  }
                }
                return this.finalize(node, new Node.IfStatement(test, consequent, alternate));
              };
              Parser2.prototype.parseDoWhileStatement = function() {
                var node = this.createNode();
                this.expectKeyword("do");
                var previousInIteration = this.context.inIteration;
                this.context.inIteration = true;
                var body = this.parseStatement();
                this.context.inIteration = previousInIteration;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                } else {
                  this.expect(")");
                  if (this.match(";")) {
                    this.nextToken();
                  }
                }
                return this.finalize(node, new Node.DoWhileStatement(body, test));
              };
              Parser2.prototype.parseWhileStatement = function() {
                var node = this.createNode();
                var body;
                this.expectKeyword("while");
                this.expect("(");
                var test = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.parseStatement();
                  this.context.inIteration = previousInIteration;
                }
                return this.finalize(node, new Node.WhileStatement(test, body));
              };
              Parser2.prototype.parseForStatement = function() {
                var init = null;
                var test = null;
                var update = null;
                var forIn = true;
                var left, right;
                var node = this.createNode();
                this.expectKeyword("for");
                this.expect("(");
                if (this.match(";")) {
                  this.nextToken();
                } else {
                  if (this.matchKeyword("var")) {
                    init = this.createNode();
                    this.nextToken();
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    var declarations = this.parseVariableDeclarationList({ inFor: true });
                    this.context.allowIn = previousAllowIn;
                    if (declarations.length === 1 && this.matchKeyword("in")) {
                      var decl = declarations[0];
                      if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) {
                        this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, "for-in");
                      }
                      init = this.finalize(init, new Node.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init;
                      right = this.parseExpression();
                      init = null;
                    } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                      init = this.finalize(init, new Node.VariableDeclaration(declarations, "var"));
                      this.nextToken();
                      left = init;
                      right = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      init = this.finalize(init, new Node.VariableDeclaration(declarations, "var"));
                      this.expect(";");
                    }
                  } else if (this.matchKeyword("const") || this.matchKeyword("let")) {
                    init = this.createNode();
                    var kind = this.nextToken().value;
                    if (!this.context.strict && this.lookahead.value === "in") {
                      init = this.finalize(init, new Node.Identifier(kind));
                      this.nextToken();
                      left = init;
                      right = this.parseExpression();
                      init = null;
                    } else {
                      var previousAllowIn = this.context.allowIn;
                      this.context.allowIn = false;
                      var declarations = this.parseBindingList(kind, { inFor: true });
                      this.context.allowIn = previousAllowIn;
                      if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword("in")) {
                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init;
                        right = this.parseExpression();
                        init = null;
                      } else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword("of")) {
                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
                        this.nextToken();
                        left = init;
                        right = this.parseAssignmentExpression();
                        init = null;
                        forIn = false;
                      } else {
                        this.consumeSemicolon();
                        init = this.finalize(init, new Node.VariableDeclaration(declarations, kind));
                      }
                    }
                  } else {
                    var initStartToken = this.lookahead;
                    var previousAllowIn = this.context.allowIn;
                    this.context.allowIn = false;
                    init = this.inheritCoverGrammar(this.parseAssignmentExpression);
                    this.context.allowIn = previousAllowIn;
                    if (this.matchKeyword("in")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForIn);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left = init;
                      right = this.parseExpression();
                      init = null;
                    } else if (this.matchContextualKeyword("of")) {
                      if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) {
                        this.tolerateError(messages_1.Messages.InvalidLHSInForLoop);
                      }
                      this.nextToken();
                      this.reinterpretExpressionAsPattern(init);
                      left = init;
                      right = this.parseAssignmentExpression();
                      init = null;
                      forIn = false;
                    } else {
                      if (this.match(",")) {
                        var initSeq = [init];
                        while (this.match(",")) {
                          this.nextToken();
                          initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression));
                        }
                        init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq));
                      }
                      this.expect(";");
                    }
                  }
                }
                if (typeof left === "undefined") {
                  if (!this.match(";")) {
                    test = this.parseExpression();
                  }
                  this.expect(";");
                  if (!this.match(")")) {
                    update = this.parseExpression();
                  }
                }
                var body;
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  var previousInIteration = this.context.inIteration;
                  this.context.inIteration = true;
                  body = this.isolateCoverGrammar(this.parseStatement);
                  this.context.inIteration = previousInIteration;
                }
                return typeof left === "undefined" ? this.finalize(node, new Node.ForStatement(init, test, update, body)) : forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : this.finalize(node, new Node.ForOfStatement(left, right, body));
              };
              Parser2.prototype.parseContinueStatement = function() {
                var node = this.createNode();
                this.expectKeyword("continue");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  label = id;
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration) {
                  this.throwError(messages_1.Messages.IllegalContinue);
                }
                return this.finalize(node, new Node.ContinueStatement(label));
              };
              Parser2.prototype.parseBreakStatement = function() {
                var node = this.createNode();
                this.expectKeyword("break");
                var label = null;
                if (this.lookahead.type === 3 && !this.hasLineTerminator) {
                  var id = this.parseVariableIdentifier();
                  var key = "$" + id.name;
                  if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.UnknownLabel, id.name);
                  }
                  label = id;
                }
                this.consumeSemicolon();
                if (label === null && !this.context.inIteration && !this.context.inSwitch) {
                  this.throwError(messages_1.Messages.IllegalBreak);
                }
                return this.finalize(node, new Node.BreakStatement(label));
              };
              Parser2.prototype.parseReturnStatement = function() {
                if (!this.context.inFunctionBody) {
                  this.tolerateError(messages_1.Messages.IllegalReturn);
                }
                var node = this.createNode();
                this.expectKeyword("return");
                var hasArgument = !this.match(";") && !this.match("}") && !this.hasLineTerminator && this.lookahead.type !== 2 || this.lookahead.type === 8 || this.lookahead.type === 10;
                var argument = hasArgument ? this.parseExpression() : null;
                this.consumeSemicolon();
                return this.finalize(node, new Node.ReturnStatement(argument));
              };
              Parser2.prototype.parseWithStatement = function() {
                if (this.context.strict) {
                  this.tolerateError(messages_1.Messages.StrictModeWith);
                }
                var node = this.createNode();
                var body;
                this.expectKeyword("with");
                this.expect("(");
                var object = this.parseExpression();
                if (!this.match(")") && this.config.tolerant) {
                  this.tolerateUnexpectedToken(this.nextToken());
                  body = this.finalize(this.createNode(), new Node.EmptyStatement());
                } else {
                  this.expect(")");
                  body = this.parseStatement();
                }
                return this.finalize(node, new Node.WithStatement(object, body));
              };
              Parser2.prototype.parseSwitchCase = function() {
                var node = this.createNode();
                var test;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  test = null;
                } else {
                  this.expectKeyword("case");
                  test = this.parseExpression();
                }
                this.expect(":");
                var consequent = [];
                while (true) {
                  if (this.match("}") || this.matchKeyword("default") || this.matchKeyword("case")) {
                    break;
                  }
                  consequent.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.SwitchCase(test, consequent));
              };
              Parser2.prototype.parseSwitchStatement = function() {
                var node = this.createNode();
                this.expectKeyword("switch");
                this.expect("(");
                var discriminant = this.parseExpression();
                this.expect(")");
                var previousInSwitch = this.context.inSwitch;
                this.context.inSwitch = true;
                var cases = [];
                var defaultFound = false;
                this.expect("{");
                while (true) {
                  if (this.match("}")) {
                    break;
                  }
                  var clause = this.parseSwitchCase();
                  if (clause.test === null) {
                    if (defaultFound) {
                      this.throwError(messages_1.Messages.MultipleDefaultsInSwitch);
                    }
                    defaultFound = true;
                  }
                  cases.push(clause);
                }
                this.expect("}");
                this.context.inSwitch = previousInSwitch;
                return this.finalize(node, new Node.SwitchStatement(discriminant, cases));
              };
              Parser2.prototype.parseLabelledStatement = function() {
                var node = this.createNode();
                var expr = this.parseExpression();
                var statement;
                if (expr.type === syntax_1.Syntax.Identifier && this.match(":")) {
                  this.nextToken();
                  var id = expr;
                  var key = "$" + id.name;
                  if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) {
                    this.throwError(messages_1.Messages.Redeclaration, "Label", id.name);
                  }
                  this.context.labelSet[key] = true;
                  var body = void 0;
                  if (this.matchKeyword("class")) {
                    this.tolerateUnexpectedToken(this.lookahead);
                    body = this.parseClassDeclaration();
                  } else if (this.matchKeyword("function")) {
                    var token = this.lookahead;
                    var declaration = this.parseFunctionDeclaration();
                    if (this.context.strict) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction);
                    } else if (declaration.generator) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext);
                    }
                    body = declaration;
                  } else {
                    body = this.parseStatement();
                  }
                  delete this.context.labelSet[key];
                  statement = new Node.LabeledStatement(id, body);
                } else {
                  this.consumeSemicolon();
                  statement = new Node.ExpressionStatement(expr);
                }
                return this.finalize(node, statement);
              };
              Parser2.prototype.parseThrowStatement = function() {
                var node = this.createNode();
                this.expectKeyword("throw");
                if (this.hasLineTerminator) {
                  this.throwError(messages_1.Messages.NewlineAfterThrow);
                }
                var argument = this.parseExpression();
                this.consumeSemicolon();
                return this.finalize(node, new Node.ThrowStatement(argument));
              };
              Parser2.prototype.parseCatchClause = function() {
                var node = this.createNode();
                this.expectKeyword("catch");
                this.expect("(");
                if (this.match(")")) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                var params = [];
                var param = this.parsePattern(params);
                var paramMap = {};
                for (var i = 0; i < params.length; i++) {
                  var key = "$" + params[i].value;
                  if (Object.prototype.hasOwnProperty.call(paramMap, key)) {
                    this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value);
                  }
                  paramMap[key] = true;
                }
                if (this.context.strict && param.type === syntax_1.Syntax.Identifier) {
                  if (this.scanner.isRestrictedWord(param.name)) {
                    this.tolerateError(messages_1.Messages.StrictCatchVariable);
                  }
                }
                this.expect(")");
                var body = this.parseBlock();
                return this.finalize(node, new Node.CatchClause(param, body));
              };
              Parser2.prototype.parseFinallyClause = function() {
                this.expectKeyword("finally");
                return this.parseBlock();
              };
              Parser2.prototype.parseTryStatement = function() {
                var node = this.createNode();
                this.expectKeyword("try");
                var block = this.parseBlock();
                var handler = this.matchKeyword("catch") ? this.parseCatchClause() : null;
                var finalizer = this.matchKeyword("finally") ? this.parseFinallyClause() : null;
                if (!handler && !finalizer) {
                  this.throwError(messages_1.Messages.NoCatchOrFinally);
                }
                return this.finalize(node, new Node.TryStatement(block, handler, finalizer));
              };
              Parser2.prototype.parseDebuggerStatement = function() {
                var node = this.createNode();
                this.expectKeyword("debugger");
                this.consumeSemicolon();
                return this.finalize(node, new Node.DebuggerStatement());
              };
              Parser2.prototype.parseStatement = function() {
                var statement;
                switch (this.lookahead.type) {
                  case 1:
                  case 5:
                  case 6:
                  case 8:
                  case 10:
                  case 9:
                    statement = this.parseExpressionStatement();
                    break;
                  case 7:
                    var value = this.lookahead.value;
                    if (value === "{") {
                      statement = this.parseBlock();
                    } else if (value === "(") {
                      statement = this.parseExpressionStatement();
                    } else if (value === ";") {
                      statement = this.parseEmptyStatement();
                    } else {
                      statement = this.parseExpressionStatement();
                    }
                    break;
                  case 3:
                    statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement();
                    break;
                  case 4:
                    switch (this.lookahead.value) {
                      case "break":
                        statement = this.parseBreakStatement();
                        break;
                      case "continue":
                        statement = this.parseContinueStatement();
                        break;
                      case "debugger":
                        statement = this.parseDebuggerStatement();
                        break;
                      case "do":
                        statement = this.parseDoWhileStatement();
                        break;
                      case "for":
                        statement = this.parseForStatement();
                        break;
                      case "function":
                        statement = this.parseFunctionDeclaration();
                        break;
                      case "if":
                        statement = this.parseIfStatement();
                        break;
                      case "return":
                        statement = this.parseReturnStatement();
                        break;
                      case "switch":
                        statement = this.parseSwitchStatement();
                        break;
                      case "throw":
                        statement = this.parseThrowStatement();
                        break;
                      case "try":
                        statement = this.parseTryStatement();
                        break;
                      case "var":
                        statement = this.parseVariableStatement();
                        break;
                      case "while":
                        statement = this.parseWhileStatement();
                        break;
                      case "with":
                        statement = this.parseWithStatement();
                        break;
                      default:
                        statement = this.parseExpressionStatement();
                        break;
                    }
                    break;
                  default:
                    statement = this.throwUnexpectedToken(this.lookahead);
                }
                return statement;
              };
              Parser2.prototype.parseFunctionSourceElements = function() {
                var node = this.createNode();
                this.expect("{");
                var body = this.parseDirectivePrologues();
                var previousLabelSet = this.context.labelSet;
                var previousInIteration = this.context.inIteration;
                var previousInSwitch = this.context.inSwitch;
                var previousInFunctionBody = this.context.inFunctionBody;
                this.context.labelSet = {};
                this.context.inIteration = false;
                this.context.inSwitch = false;
                this.context.inFunctionBody = true;
                while (this.lookahead.type !== 2) {
                  if (this.match("}")) {
                    break;
                  }
                  body.push(this.parseStatementListItem());
                }
                this.expect("}");
                this.context.labelSet = previousLabelSet;
                this.context.inIteration = previousInIteration;
                this.context.inSwitch = previousInSwitch;
                this.context.inFunctionBody = previousInFunctionBody;
                return this.finalize(node, new Node.BlockStatement(body));
              };
              Parser2.prototype.validateParam = function(options, param, name) {
                var key = "$" + name;
                if (this.context.strict) {
                  if (this.scanner.isRestrictedWord(name)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamName;
                  }
                  if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamDupe;
                  }
                } else if (!options.firstRestricted) {
                  if (this.scanner.isRestrictedWord(name)) {
                    options.firstRestricted = param;
                    options.message = messages_1.Messages.StrictParamName;
                  } else if (this.scanner.isStrictModeReservedWord(name)) {
                    options.firstRestricted = param;
                    options.message = messages_1.Messages.StrictReservedWord;
                  } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) {
                    options.stricted = param;
                    options.message = messages_1.Messages.StrictParamDupe;
                  }
                }
                if (typeof Object.defineProperty === "function") {
                  Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true });
                } else {
                  options.paramSet[key] = true;
                }
              };
              Parser2.prototype.parseRestElement = function(params) {
                var node = this.createNode();
                this.expect("...");
                var arg = this.parsePattern(params);
                if (this.match("=")) {
                  this.throwError(messages_1.Messages.DefaultRestParameter);
                }
                if (!this.match(")")) {
                  this.throwError(messages_1.Messages.ParameterAfterRestParameter);
                }
                return this.finalize(node, new Node.RestElement(arg));
              };
              Parser2.prototype.parseFormalParameter = function(options) {
                var params = [];
                var param = this.match("...") ? this.parseRestElement(params) : this.parsePatternWithDefault(params);
                for (var i = 0; i < params.length; i++) {
                  this.validateParam(options, params[i], params[i].value);
                }
                options.simple = options.simple && param instanceof Node.Identifier;
                options.params.push(param);
              };
              Parser2.prototype.parseFormalParameters = function(firstRestricted) {
                var options;
                options = {
                  simple: true,
                  params: [],
                  firstRestricted
                };
                this.expect("(");
                if (!this.match(")")) {
                  options.paramSet = {};
                  while (this.lookahead.type !== 2) {
                    this.parseFormalParameter(options);
                    if (this.match(")")) {
                      break;
                    }
                    this.expect(",");
                    if (this.match(")")) {
                      break;
                    }
                  }
                }
                this.expect(")");
                return {
                  simple: options.simple,
                  params: options.params,
                  stricted: options.stricted,
                  firstRestricted: options.firstRestricted,
                  message: options.message
                };
              };
              Parser2.prototype.matchAsyncFunction = function() {
                var match = this.matchContextualKeyword("async");
                if (match) {
                  var state = this.scanner.saveState();
                  this.scanner.scanComments();
                  var next = this.scanner.lex();
                  this.scanner.restoreState(state);
                  match = state.lineNumber === next.lineNumber && next.type === 4 && next.value === "function";
                }
                return match;
              };
              Parser2.prototype.parseFunctionDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted = null;
                if (!identifierIsOptional || !this.match("(")) {
                  var token = this.lookahead;
                  id = this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator));
              };
              Parser2.prototype.parseFunctionExpression = function() {
                var node = this.createNode();
                var isAsync = this.matchContextualKeyword("async");
                if (isAsync) {
                  this.nextToken();
                }
                this.expectKeyword("function");
                var isGenerator = isAsync ? false : this.match("*");
                if (isGenerator) {
                  this.nextToken();
                }
                var message;
                var id = null;
                var firstRestricted;
                var previousAllowAwait = this.context.await;
                var previousAllowYield = this.context.allowYield;
                this.context.await = isAsync;
                this.context.allowYield = !isGenerator;
                if (!this.match("(")) {
                  var token = this.lookahead;
                  id = !this.context.strict && !isGenerator && this.matchKeyword("yield") ? this.parseIdentifierName() : this.parseVariableIdentifier();
                  if (this.context.strict) {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName);
                    }
                  } else {
                    if (this.scanner.isRestrictedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictFunctionName;
                    } else if (this.scanner.isStrictModeReservedWord(token.value)) {
                      firstRestricted = token;
                      message = messages_1.Messages.StrictReservedWord;
                    }
                  }
                }
                var formalParameters = this.parseFormalParameters(firstRestricted);
                var params = formalParameters.params;
                var stricted = formalParameters.stricted;
                firstRestricted = formalParameters.firstRestricted;
                if (formalParameters.message) {
                  message = formalParameters.message;
                }
                var previousStrict = this.context.strict;
                var previousAllowStrictDirective = this.context.allowStrictDirective;
                this.context.allowStrictDirective = formalParameters.simple;
                var body = this.parseFunctionSourceElements();
                if (this.context.strict && firstRestricted) {
                  this.throwUnexpectedToken(firstRestricted, message);
                }
                if (this.context.strict && stricted) {
                  this.tolerateUnexpectedToken(stricted, message);
                }
                this.context.strict = previousStrict;
                this.context.allowStrictDirective = previousAllowStrictDirective;
                this.context.await = previousAllowAwait;
                this.context.allowYield = previousAllowYield;
                return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator));
              };
              Parser2.prototype.parseDirective = function() {
                var token = this.lookahead;
                var node = this.createNode();
                var expr = this.parseExpression();
                var directive = expr.type === syntax_1.Syntax.Literal ? this.getTokenRaw(token).slice(1, -1) : null;
                this.consumeSemicolon();
                return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr));
              };
              Parser2.prototype.parseDirectivePrologues = function() {
                var firstRestricted = null;
                var body = [];
                while (true) {
                  var token = this.lookahead;
                  if (token.type !== 8) {
                    break;
                  }
                  var statement = this.parseDirective();
                  body.push(statement);
                  var directive = statement.directive;
                  if (typeof directive !== "string") {
                    break;
                  }
                  if (directive === "use strict") {
                    this.context.strict = true;
                    if (firstRestricted) {
                      this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral);
                    }
                    if (!this.context.allowStrictDirective) {
                      this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective);
                    }
                  } else {
                    if (!firstRestricted && token.octal) {
                      firstRestricted = token;
                    }
                  }
                }
                return body;
              };
              Parser2.prototype.qualifiedPropertyName = function(token) {
                switch (token.type) {
                  case 3:
                  case 8:
                  case 1:
                  case 5:
                  case 6:
                  case 4:
                    return true;
                  case 7:
                    return token.value === "[";
                  default:
                    break;
                }
                return false;
              };
              Parser2.prototype.parseGetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length > 0) {
                  this.tolerateError(messages_1.Messages.BadGetterArity);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser2.prototype.parseSetterMethod = function() {
                var node = this.createNode();
                var isGenerator = false;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = !isGenerator;
                var formalParameters = this.parseFormalParameters();
                if (formalParameters.params.length !== 1) {
                  this.tolerateError(messages_1.Messages.BadSetterArity);
                } else if (formalParameters.params[0] instanceof Node.RestElement) {
                  this.tolerateError(messages_1.Messages.BadSetterRestParameter);
                }
                var method = this.parsePropertyMethod(formalParameters);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator));
              };
              Parser2.prototype.parseGeneratorMethod = function() {
                var node = this.createNode();
                var isGenerator = true;
                var previousAllowYield = this.context.allowYield;
                this.context.allowYield = true;
                var params = this.parseFormalParameters();
                this.context.allowYield = false;
                var method = this.parsePropertyMethod(params);
                this.context.allowYield = previousAllowYield;
                return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator));
              };
              Parser2.prototype.isStartOfExpression = function() {
                var start = true;
                var value = this.lookahead.value;
                switch (this.lookahead.type) {
                  case 7:
                    start = value === "[" || value === "(" || value === "{" || value === "+" || value === "-" || value === "!" || value === "~" || value === "++" || value === "--" || value === "/" || value === "/=";
                    break;
                  case 4:
                    start = value === "class" || value === "delete" || value === "function" || value === "let" || value === "new" || value === "super" || value === "this" || value === "typeof" || value === "void" || value === "yield";
                    break;
                  default:
                    break;
                }
                return start;
              };
              Parser2.prototype.parseYieldExpression = function() {
                var node = this.createNode();
                this.expectKeyword("yield");
                var argument = null;
                var delegate = false;
                if (!this.hasLineTerminator) {
                  var previousAllowYield = this.context.allowYield;
                  this.context.allowYield = false;
                  delegate = this.match("*");
                  if (delegate) {
                    this.nextToken();
                    argument = this.parseAssignmentExpression();
                  } else if (this.isStartOfExpression()) {
                    argument = this.parseAssignmentExpression();
                  }
                  this.context.allowYield = previousAllowYield;
                }
                return this.finalize(node, new Node.YieldExpression(argument, delegate));
              };
              Parser2.prototype.parseClassElement = function(hasConstructor) {
                var token = this.lookahead;
                var node = this.createNode();
                var kind = "";
                var key = null;
                var value = null;
                var computed = false;
                var method = false;
                var isStatic = false;
                var isAsync = false;
                if (this.match("*")) {
                  this.nextToken();
                } else {
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  var id = key;
                  if (id.name === "static" && (this.qualifiedPropertyName(this.lookahead) || this.match("*"))) {
                    token = this.lookahead;
                    isStatic = true;
                    computed = this.match("[");
                    if (this.match("*")) {
                      this.nextToken();
                    } else {
                      key = this.parseObjectPropertyKey();
                    }
                  }
                  if (token.type === 3 && !this.hasLineTerminator && token.value === "async") {
                    var punctuator = this.lookahead.value;
                    if (punctuator !== ":" && punctuator !== "(" && punctuator !== "*") {
                      isAsync = true;
                      token = this.lookahead;
                      key = this.parseObjectPropertyKey();
                      if (token.type === 3 && token.value === "constructor") {
                        this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync);
                      }
                    }
                  }
                }
                var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead);
                if (token.type === 3) {
                  if (token.value === "get" && lookaheadPropertyKey) {
                    kind = "get";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    this.context.allowYield = false;
                    value = this.parseGetterMethod();
                  } else if (token.value === "set" && lookaheadPropertyKey) {
                    kind = "set";
                    computed = this.match("[");
                    key = this.parseObjectPropertyKey();
                    value = this.parseSetterMethod();
                  }
                } else if (token.type === 7 && token.value === "*" && lookaheadPropertyKey) {
                  kind = "init";
                  computed = this.match("[");
                  key = this.parseObjectPropertyKey();
                  value = this.parseGeneratorMethod();
                  method = true;
                }
                if (!kind && key && this.match("(")) {
                  kind = "init";
                  value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction();
                  method = true;
                }
                if (!kind) {
                  this.throwUnexpectedToken(this.lookahead);
                }
                if (kind === "init") {
                  kind = "method";
                }
                if (!computed) {
                  if (isStatic && this.isPropertyKey(key, "prototype")) {
                    this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype);
                  }
                  if (!isStatic && this.isPropertyKey(key, "constructor")) {
                    if (kind !== "method" || !method || value && value.generator) {
                      this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod);
                    }
                    if (hasConstructor.value) {
                      this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor);
                    } else {
                      hasConstructor.value = true;
                    }
                    kind = "constructor";
                  }
                }
                return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic));
              };
              Parser2.prototype.parseClassElementList = function() {
                var body = [];
                var hasConstructor = { value: false };
                this.expect("{");
                while (!this.match("}")) {
                  if (this.match(";")) {
                    this.nextToken();
                  } else {
                    body.push(this.parseClassElement(hasConstructor));
                  }
                }
                this.expect("}");
                return body;
              };
              Parser2.prototype.parseClassBody = function() {
                var node = this.createNode();
                var elementList = this.parseClassElementList();
                return this.finalize(node, new Node.ClassBody(elementList));
              };
              Parser2.prototype.parseClassDeclaration = function(identifierIsOptional) {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = identifierIsOptional && this.lookahead.type !== 3 ? null : this.parseVariableIdentifier();
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody));
              };
              Parser2.prototype.parseClassExpression = function() {
                var node = this.createNode();
                var previousStrict = this.context.strict;
                this.context.strict = true;
                this.expectKeyword("class");
                var id = this.lookahead.type === 3 ? this.parseVariableIdentifier() : null;
                var superClass = null;
                if (this.matchKeyword("extends")) {
                  this.nextToken();
                  superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall);
                }
                var classBody = this.parseClassBody();
                this.context.strict = previousStrict;
                return this.finalize(node, new Node.ClassExpression(id, superClass, classBody));
              };
              Parser2.prototype.parseModule = function() {
                this.context.strict = true;
                this.context.isModule = true;
                this.scanner.isModule = true;
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.Module(body));
              };
              Parser2.prototype.parseScript = function() {
                var node = this.createNode();
                var body = this.parseDirectivePrologues();
                while (this.lookahead.type !== 2) {
                  body.push(this.parseStatementListItem());
                }
                return this.finalize(node, new Node.Script(body));
              };
              Parser2.prototype.parseModuleSpecifier = function() {
                var node = this.createNode();
                if (this.lookahead.type !== 8) {
                  this.throwError(messages_1.Messages.InvalidModuleSpecifier);
                }
                var token = this.nextToken();
                var raw = this.getTokenRaw(token);
                return this.finalize(node, new Node.Literal(token.value, raw));
              };
              Parser2.prototype.parseImportSpecifier = function() {
                var node = this.createNode();
                var imported;
                var local;
                if (this.lookahead.type === 3) {
                  imported = this.parseVariableIdentifier();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  }
                } else {
                  imported = this.parseIdentifierName();
                  local = imported;
                  if (this.matchContextualKeyword("as")) {
                    this.nextToken();
                    local = this.parseVariableIdentifier();
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                }
                return this.finalize(node, new Node.ImportSpecifier(local, imported));
              };
              Parser2.prototype.parseNamedImports = function() {
                this.expect("{");
                var specifiers = [];
                while (!this.match("}")) {
                  specifiers.push(this.parseImportSpecifier());
                  if (!this.match("}")) {
                    this.expect(",");
                  }
                }
                this.expect("}");
                return specifiers;
              };
              Parser2.prototype.parseImportDefaultSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node.ImportDefaultSpecifier(local));
              };
              Parser2.prototype.parseImportNamespaceSpecifier = function() {
                var node = this.createNode();
                this.expect("*");
                if (!this.matchContextualKeyword("as")) {
                  this.throwError(messages_1.Messages.NoAsAfterImportNamespace);
                }
                this.nextToken();
                var local = this.parseIdentifierName();
                return this.finalize(node, new Node.ImportNamespaceSpecifier(local));
              };
              Parser2.prototype.parseImportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalImportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("import");
                var src;
                var specifiers = [];
                if (this.lookahead.type === 8) {
                  src = this.parseModuleSpecifier();
                } else {
                  if (this.match("{")) {
                    specifiers = specifiers.concat(this.parseNamedImports());
                  } else if (this.match("*")) {
                    specifiers.push(this.parseImportNamespaceSpecifier());
                  } else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword("default")) {
                    specifiers.push(this.parseImportDefaultSpecifier());
                    if (this.match(",")) {
                      this.nextToken();
                      if (this.match("*")) {
                        specifiers.push(this.parseImportNamespaceSpecifier());
                      } else if (this.match("{")) {
                        specifiers = specifiers.concat(this.parseNamedImports());
                      } else {
                        this.throwUnexpectedToken(this.lookahead);
                      }
                    }
                  } else {
                    this.throwUnexpectedToken(this.nextToken());
                  }
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  src = this.parseModuleSpecifier();
                }
                this.consumeSemicolon();
                return this.finalize(node, new Node.ImportDeclaration(specifiers, src));
              };
              Parser2.prototype.parseExportSpecifier = function() {
                var node = this.createNode();
                var local = this.parseIdentifierName();
                var exported = local;
                if (this.matchContextualKeyword("as")) {
                  this.nextToken();
                  exported = this.parseIdentifierName();
                }
                return this.finalize(node, new Node.ExportSpecifier(local, exported));
              };
              Parser2.prototype.parseExportDeclaration = function() {
                if (this.context.inFunctionBody) {
                  this.throwError(messages_1.Messages.IllegalExportDeclaration);
                }
                var node = this.createNode();
                this.expectKeyword("export");
                var exportDeclaration;
                if (this.matchKeyword("default")) {
                  this.nextToken();
                  if (this.matchKeyword("function")) {
                    var declaration = this.parseFunctionDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else if (this.matchKeyword("class")) {
                    var declaration = this.parseClassDeclaration(true);
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else if (this.matchContextualKeyword("async")) {
                    var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression();
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  } else {
                    if (this.matchContextualKeyword("from")) {
                      this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value);
                    }
                    var declaration = this.match("{") ? this.parseObjectInitializer() : this.match("[") ? this.parseArrayInitializer() : this.parseAssignmentExpression();
                    this.consumeSemicolon();
                    exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration));
                  }
                } else if (this.match("*")) {
                  this.nextToken();
                  if (!this.matchContextualKeyword("from")) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  }
                  this.nextToken();
                  var src = this.parseModuleSpecifier();
                  this.consumeSemicolon();
                  exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src));
                } else if (this.lookahead.type === 4) {
                  var declaration = void 0;
                  switch (this.lookahead.value) {
                    case "let":
                    case "const":
                      declaration = this.parseLexicalDeclaration({ inFor: false });
                      break;
                    case "var":
                    case "class":
                    case "function":
                      declaration = this.parseStatementListItem();
                      break;
                    default:
                      this.throwUnexpectedToken(this.lookahead);
                  }
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
                } else if (this.matchAsyncFunction()) {
                  var declaration = this.parseFunctionDeclaration();
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null));
                } else {
                  var specifiers = [];
                  var source = null;
                  var isExportFromIdentifier = false;
                  this.expect("{");
                  while (!this.match("}")) {
                    isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword("default");
                    specifiers.push(this.parseExportSpecifier());
                    if (!this.match("}")) {
                      this.expect(",");
                    }
                  }
                  this.expect("}");
                  if (this.matchContextualKeyword("from")) {
                    this.nextToken();
                    source = this.parseModuleSpecifier();
                    this.consumeSemicolon();
                  } else if (isExportFromIdentifier) {
                    var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause;
                    this.throwError(message, this.lookahead.value);
                  } else {
                    this.consumeSemicolon();
                  }
                  exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source));
                }
                return exportDeclaration;
              };
              return Parser2;
            }();
            exports2.Parser = Parser;
          },
          /* 9 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            function assert(condition, message) {
              if (!condition) {
                throw new Error("ASSERT: " + message);
              }
            }
            __name(assert, "assert");
            exports2.assert = assert;
          },
          /* 10 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var ErrorHandler = function() {
              function ErrorHandler2() {
                this.errors = [];
                this.tolerant = false;
              }
              __name(ErrorHandler2, "ErrorHandler");
              ErrorHandler2.prototype.recordError = function(error) {
                this.errors.push(error);
              };
              ErrorHandler2.prototype.tolerate = function(error) {
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              ErrorHandler2.prototype.constructError = function(msg, column) {
                var error = new Error(msg);
                try {
                  throw error;
                } catch (base) {
                  if (Object.create && Object.defineProperty) {
                    error = Object.create(base);
                    Object.defineProperty(error, "column", { value: column });
                  }
                }
                return error;
              };
              ErrorHandler2.prototype.createError = function(index, line, col, description) {
                var msg = "Line " + line + ": " + description;
                var error = this.constructError(msg, col);
                error.index = index;
                error.lineNumber = line;
                error.description = description;
                return error;
              };
              ErrorHandler2.prototype.throwError = function(index, line, col, description) {
                throw this.createError(index, line, col, description);
              };
              ErrorHandler2.prototype.tolerateError = function(index, line, col, description) {
                var error = this.createError(index, line, col, description);
                if (this.tolerant) {
                  this.recordError(error);
                } else {
                  throw error;
                }
              };
              return ErrorHandler2;
            }();
            exports2.ErrorHandler = ErrorHandler;
          },
          /* 11 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            exports2.Messages = {
              BadGetterArity: "Getter must not have any formal parameters",
              BadSetterArity: "Setter must have exactly one formal parameter",
              BadSetterRestParameter: "Setter function argument must not be a rest parameter",
              ConstructorIsAsync: "Class constructor may not be an async method",
              ConstructorSpecialMethod: "Class constructor may not be an accessor",
              DeclarationMissingInitializer: "Missing initializer in %0 declaration",
              DefaultRestParameter: "Unexpected token =",
              DuplicateBinding: "Duplicate binding %0",
              DuplicateConstructor: "A class may only have one constructor",
              DuplicateProtoProperty: "Duplicate __proto__ fields are not allowed in object literals",
              ForInOfLoopInitializer: "%0 loop variable declaration may not have an initializer",
              GeneratorInLegacyContext: "Generator declarations are not allowed in legacy contexts",
              IllegalBreak: "Illegal break statement",
              IllegalContinue: "Illegal continue statement",
              IllegalExportDeclaration: "Unexpected token",
              IllegalImportDeclaration: "Unexpected token",
              IllegalLanguageModeDirective: "Illegal 'use strict' directive in function with non-simple parameter list",
              IllegalReturn: "Illegal return statement",
              InvalidEscapedReservedWord: "Keyword must not contain escaped characters",
              InvalidHexEscapeSequence: "Invalid hexadecimal escape sequence",
              InvalidLHSInAssignment: "Invalid left-hand side in assignment",
              InvalidLHSInForIn: "Invalid left-hand side in for-in",
              InvalidLHSInForLoop: "Invalid left-hand side in for-loop",
              InvalidModuleSpecifier: "Unexpected token",
              InvalidRegExp: "Invalid regular expression",
              LetInLexicalBinding: "let is disallowed as a lexically bound name",
              MissingFromClause: "Unexpected token",
              MultipleDefaultsInSwitch: "More than one default clause in switch statement",
              NewlineAfterThrow: "Illegal newline after throw",
              NoAsAfterImportNamespace: "Unexpected token",
              NoCatchOrFinally: "Missing catch or finally after try",
              ParameterAfterRestParameter: "Rest parameter must be last formal parameter",
              Redeclaration: "%0 '%1' has already been declared",
              StaticPrototype: "Classes may not have static property named prototype",
              StrictCatchVariable: "Catch variable may not be eval or arguments in strict mode",
              StrictDelete: "Delete of an unqualified identifier in strict mode.",
              StrictFunction: "In strict mode code, functions can only be declared at top level or inside a block",
              StrictFunctionName: "Function name may not be eval or arguments in strict mode",
              StrictLHSAssignment: "Assignment to eval or arguments is not allowed in strict mode",
              StrictLHSPostfix: "Postfix increment/decrement may not have eval or arguments operand in strict mode",
              StrictLHSPrefix: "Prefix increment/decrement may not have eval or arguments operand in strict mode",
              StrictModeWith: "Strict mode code may not include a with statement",
              StrictOctalLiteral: "Octal literals are not allowed in strict mode.",
              StrictParamDupe: "Strict mode function may not have duplicate parameter names",
              StrictParamName: "Parameter name eval or arguments is not allowed in strict mode",
              StrictReservedWord: "Use of future reserved word in strict mode",
              StrictVarName: "Variable name may not be eval or arguments in strict mode",
              TemplateOctalLiteral: "Octal literals are not allowed in template strings.",
              UnexpectedEOS: "Unexpected end of input",
              UnexpectedIdentifier: "Unexpected identifier",
              UnexpectedNumber: "Unexpected number",
              UnexpectedReserved: "Unexpected reserved word",
              UnexpectedString: "Unexpected string",
              UnexpectedTemplate: "Unexpected quasi %0",
              UnexpectedToken: "Unexpected token %0",
              UnexpectedTokenIllegal: "Unexpected token ILLEGAL",
              UnknownLabel: "Undefined label '%0'",
              UnterminatedRegExp: "Invalid regular expression: missing /"
            };
          },
          /* 12 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var assert_1 = __webpack_require__(9);
            var character_1 = __webpack_require__(4);
            var messages_1 = __webpack_require__(11);
            function hexValue(ch) {
              return "0123456789abcdef".indexOf(ch.toLowerCase());
            }
            __name(hexValue, "hexValue");
            function octalValue(ch) {
              return "01234567".indexOf(ch);
            }
            __name(octalValue, "octalValue");
            var Scanner = function() {
              function Scanner2(code, handler) {
                this.source = code;
                this.errorHandler = handler;
                this.trackComment = false;
                this.isModule = false;
                this.length = code.length;
                this.index = 0;
                this.lineNumber = code.length > 0 ? 1 : 0;
                this.lineStart = 0;
                this.curlyStack = [];
              }
              __name(Scanner2, "Scanner");
              Scanner2.prototype.saveState = function() {
                return {
                  index: this.index,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart
                };
              };
              Scanner2.prototype.restoreState = function(state) {
                this.index = state.index;
                this.lineNumber = state.lineNumber;
                this.lineStart = state.lineStart;
              };
              Scanner2.prototype.eof = function() {
                return this.index >= this.length;
              };
              Scanner2.prototype.throwUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.tolerateUnexpectedToken = function(message) {
                if (message === void 0) {
                  message = messages_1.Messages.UnexpectedTokenIllegal;
                }
                this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message);
              };
              Scanner2.prototype.skipSingleLineComment = function(offset) {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - offset;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - offset
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  ++this.index;
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (this.trackComment) {
                      loc.end = {
                        line: this.lineNumber,
                        column: this.index - this.lineStart - 1
                      };
                      var entry = {
                        multiLine: false,
                        slice: [start + offset, this.index - 1],
                        range: [start, this.index - 1],
                        loc
                      };
                      comments.push(entry);
                    }
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    return comments;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: false,
                    slice: [start + offset, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                return comments;
              };
              Scanner2.prototype.skipMultiLineComment = function() {
                var comments = [];
                var start, loc;
                if (this.trackComment) {
                  comments = [];
                  start = this.index - 2;
                  loc = {
                    start: {
                      line: this.lineNumber,
                      column: this.index - this.lineStart - 2
                    },
                    end: {}
                  };
                }
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isLineTerminator(ch)) {
                    if (ch === 13 && this.source.charCodeAt(this.index + 1) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    ++this.index;
                    this.lineStart = this.index;
                  } else if (ch === 42) {
                    if (this.source.charCodeAt(this.index + 1) === 47) {
                      this.index += 2;
                      if (this.trackComment) {
                        loc.end = {
                          line: this.lineNumber,
                          column: this.index - this.lineStart
                        };
                        var entry = {
                          multiLine: true,
                          slice: [start + 2, this.index - 2],
                          range: [start, this.index],
                          loc
                        };
                        comments.push(entry);
                      }
                      return comments;
                    }
                    ++this.index;
                  } else {
                    ++this.index;
                  }
                }
                if (this.trackComment) {
                  loc.end = {
                    line: this.lineNumber,
                    column: this.index - this.lineStart
                  };
                  var entry = {
                    multiLine: true,
                    slice: [start + 2, this.index],
                    range: [start, this.index],
                    loc
                  };
                  comments.push(entry);
                }
                this.tolerateUnexpectedToken();
                return comments;
              };
              Scanner2.prototype.scanComments = function() {
                var comments;
                if (this.trackComment) {
                  comments = [];
                }
                var start = this.index === 0;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isWhiteSpace(ch)) {
                    ++this.index;
                  } else if (character_1.Character.isLineTerminator(ch)) {
                    ++this.index;
                    if (ch === 13 && this.source.charCodeAt(this.index) === 10) {
                      ++this.index;
                    }
                    ++this.lineNumber;
                    this.lineStart = this.index;
                    start = true;
                  } else if (ch === 47) {
                    ch = this.source.charCodeAt(this.index + 1);
                    if (ch === 47) {
                      this.index += 2;
                      var comment = this.skipSingleLineComment(2);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                      start = true;
                    } else if (ch === 42) {
                      this.index += 2;
                      var comment = this.skipMultiLineComment();
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (start && ch === 45) {
                    if (this.source.charCodeAt(this.index + 1) === 45 && this.source.charCodeAt(this.index + 2) === 62) {
                      this.index += 3;
                      var comment = this.skipSingleLineComment(3);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else if (ch === 60 && !this.isModule) {
                    if (this.source.slice(this.index + 1, this.index + 4) === "!--") {
                      this.index += 4;
                      var comment = this.skipSingleLineComment(4);
                      if (this.trackComment) {
                        comments = comments.concat(comment);
                      }
                    } else {
                      break;
                    }
                  } else {
                    break;
                  }
                }
                return comments;
              };
              Scanner2.prototype.isFutureReservedWord = function(id) {
                switch (id) {
                  case "enum":
                  case "export":
                  case "import":
                  case "super":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isStrictModeReservedWord = function(id) {
                switch (id) {
                  case "implements":
                  case "interface":
                  case "package":
                  case "private":
                  case "protected":
                  case "public":
                  case "static":
                  case "yield":
                  case "let":
                    return true;
                  default:
                    return false;
                }
              };
              Scanner2.prototype.isRestrictedWord = function(id) {
                return id === "eval" || id === "arguments";
              };
              Scanner2.prototype.isKeyword = function(id) {
                switch (id.length) {
                  case 2:
                    return id === "if" || id === "in" || id === "do";
                  case 3:
                    return id === "var" || id === "for" || id === "new" || id === "try" || id === "let";
                  case 4:
                    return id === "this" || id === "else" || id === "case" || id === "void" || id === "with" || id === "enum";
                  case 5:
                    return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const" || id === "yield" || id === "class" || id === "super";
                  case 6:
                    return id === "return" || id === "typeof" || id === "delete" || id === "switch" || id === "export" || id === "import";
                  case 7:
                    return id === "default" || id === "finally" || id === "extends";
                  case 8:
                    return id === "function" || id === "continue" || id === "debugger";
                  case 10:
                    return id === "instanceof";
                  default:
                    return false;
                }
              };
              Scanner2.prototype.codePointAt = function(i) {
                var cp = this.source.charCodeAt(i);
                if (cp >= 55296 && cp <= 56319) {
                  var second = this.source.charCodeAt(i + 1);
                  if (second >= 56320 && second <= 57343) {
                    var first = cp;
                    cp = (first - 55296) * 1024 + second - 56320 + 65536;
                  }
                }
                return cp;
              };
              Scanner2.prototype.scanHexEscape = function(prefix) {
                var len = prefix === "u" ? 4 : 2;
                var code = 0;
                for (var i = 0; i < len; ++i) {
                  if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    code = code * 16 + hexValue(this.source[this.index++]);
                  } else {
                    return null;
                  }
                }
                return String.fromCharCode(code);
              };
              Scanner2.prototype.scanUnicodeCodePointEscape = function() {
                var ch = this.source[this.index];
                var code = 0;
                if (ch === "}") {
                  this.throwUnexpectedToken();
                }
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) {
                    break;
                  }
                  code = code * 16 + hexValue(ch);
                }
                if (code > 1114111 || ch !== "}") {
                  this.throwUnexpectedToken();
                }
                return character_1.Character.fromCodePoint(code);
              };
              Scanner2.prototype.getIdentifier = function() {
                var start = this.index++;
                while (!this.eof()) {
                  var ch = this.source.charCodeAt(this.index);
                  if (ch === 92) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  } else if (ch >= 55296 && ch < 57343) {
                    this.index = start;
                    return this.getComplexIdentifier();
                  }
                  if (character_1.Character.isIdentifierPart(ch)) {
                    ++this.index;
                  } else {
                    break;
                  }
                }
                return this.source.slice(start, this.index);
              };
              Scanner2.prototype.getComplexIdentifier = function() {
                var cp = this.codePointAt(this.index);
                var id = character_1.Character.fromCodePoint(cp);
                this.index += id.length;
                var ch;
                if (cp === 92) {
                  if (this.source.charCodeAt(this.index) !== 117) {
                    this.throwUnexpectedToken();
                  }
                  ++this.index;
                  if (this.source[this.index] === "{") {
                    ++this.index;
                    ch = this.scanUnicodeCodePointEscape();
                  } else {
                    ch = this.scanHexEscape("u");
                    if (ch === null || ch === "\\" || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken();
                    }
                  }
                  id = ch;
                }
                while (!this.eof()) {
                  cp = this.codePointAt(this.index);
                  if (!character_1.Character.isIdentifierPart(cp)) {
                    break;
                  }
                  ch = character_1.Character.fromCodePoint(cp);
                  id += ch;
                  this.index += ch.length;
                  if (cp === 92) {
                    id = id.substr(0, id.length - 1);
                    if (this.source.charCodeAt(this.index) !== 117) {
                      this.throwUnexpectedToken();
                    }
                    ++this.index;
                    if (this.source[this.index] === "{") {
                      ++this.index;
                      ch = this.scanUnicodeCodePointEscape();
                    } else {
                      ch = this.scanHexEscape("u");
                      if (ch === null || ch === "\\" || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                        this.throwUnexpectedToken();
                      }
                    }
                    id += ch;
                  }
                }
                return id;
              };
              Scanner2.prototype.octalToDecimal = function(ch) {
                var octal = ch !== "0";
                var code = octalValue(ch);
                if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                  octal = true;
                  code = code * 8 + octalValue(this.source[this.index++]);
                  if ("0123".indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    code = code * 8 + octalValue(this.source[this.index++]);
                  }
                }
                return {
                  code,
                  octal
                };
              };
              Scanner2.prototype.scanIdentifier = function() {
                var type;
                var start = this.index;
                var id = this.source.charCodeAt(start) === 92 ? this.getComplexIdentifier() : this.getIdentifier();
                if (id.length === 1) {
                  type = 3;
                } else if (this.isKeyword(id)) {
                  type = 4;
                } else if (id === "null") {
                  type = 5;
                } else if (id === "true" || id === "false") {
                  type = 1;
                } else {
                  type = 3;
                }
                if (type !== 3 && start + id.length !== this.index) {
                  var restore = this.index;
                  this.index = start;
                  this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord);
                  this.index = restore;
                }
                return {
                  type,
                  value: id,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanPunctuator = function() {
                var start = this.index;
                var str = this.source[this.index];
                switch (str) {
                  case "(":
                  case "{":
                    if (str === "{") {
                      this.curlyStack.push("{");
                    }
                    ++this.index;
                    break;
                  case ".":
                    ++this.index;
                    if (this.source[this.index] === "." && this.source[this.index + 1] === ".") {
                      this.index += 2;
                      str = "...";
                    }
                    break;
                  case "}":
                    ++this.index;
                    this.curlyStack.pop();
                    break;
                  case ")":
                  case ";":
                  case ",":
                  case "[":
                  case "]":
                  case ":":
                  case "?":
                  case "~":
                    ++this.index;
                    break;
                  default:
                    str = this.source.substr(this.index, 4);
                    if (str === ">>>=") {
                      this.index += 4;
                    } else {
                      str = str.substr(0, 3);
                      if (str === "===" || str === "!==" || str === ">>>" || str === "<<=" || str === ">>=" || str === "**=") {
                        this.index += 3;
                      } else {
                        str = str.substr(0, 2);
                        if (str === "&&" || str === "||" || str === "==" || str === "!=" || str === "+=" || str === "-=" || str === "*=" || str === "/=" || str === "++" || str === "--" || str === "<<" || str === ">>" || str === "&=" || str === "|=" || str === "^=" || str === "%=" || str === "<=" || str === ">=" || str === "=>" || str === "**") {
                          this.index += 2;
                        } else {
                          str = this.source[this.index];
                          if ("<>=!+-*%&|^/".indexOf(str) >= 0) {
                            ++this.index;
                          }
                        }
                      }
                    }
                }
                if (this.index === start) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 7,
                  value: str,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanHexLiteral = function(start) {
                var num = "";
                while (!this.eof()) {
                  if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt("0x" + num, 16),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanBinaryLiteral = function(start) {
                var num = "";
                var ch;
                while (!this.eof()) {
                  ch = this.source[this.index];
                  if (ch !== "0" && ch !== "1") {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (!this.eof()) {
                  ch = this.source.charCodeAt(this.index);
                  if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) {
                    this.throwUnexpectedToken();
                  }
                }
                return {
                  type: 6,
                  value: parseInt(num, 2),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanOctalLiteral = function(prefix, start) {
                var num = "";
                var octal = false;
                if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) {
                  octal = true;
                  num = "0" + this.source[this.index++];
                } else {
                  ++this.index;
                }
                while (!this.eof()) {
                  if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) {
                    break;
                  }
                  num += this.source[this.index++];
                }
                if (!octal && num.length === 0) {
                  this.throwUnexpectedToken();
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseInt(num, 8),
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.isImplicitOctalLiteral = function() {
                for (var i = this.index + 1; i < this.length; ++i) {
                  var ch = this.source[i];
                  if (ch === "8" || ch === "9") {
                    return false;
                  }
                  if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                    return true;
                  }
                }
                return true;
              };
              Scanner2.prototype.scanNumericLiteral = function() {
                var start = this.index;
                var ch = this.source[start];
                assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || ch === ".", "Numeric literal must start with a decimal digit or a decimal point");
                var num = "";
                if (ch !== ".") {
                  num = this.source[this.index++];
                  ch = this.source[this.index];
                  if (num === "0") {
                    if (ch === "x" || ch === "X") {
                      ++this.index;
                      return this.scanHexLiteral(start);
                    }
                    if (ch === "b" || ch === "B") {
                      ++this.index;
                      return this.scanBinaryLiteral(start);
                    }
                    if (ch === "o" || ch === "O") {
                      return this.scanOctalLiteral(ch, start);
                    }
                    if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                      if (this.isImplicitOctalLiteral()) {
                        return this.scanOctalLiteral(ch, start);
                      }
                    }
                  }
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === ".") {
                  num += this.source[this.index++];
                  while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    num += this.source[this.index++];
                  }
                  ch = this.source[this.index];
                }
                if (ch === "e" || ch === "E") {
                  num += this.source[this.index++];
                  ch = this.source[this.index];
                  if (ch === "+" || ch === "-") {
                    num += this.source[this.index++];
                  }
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                    while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                      num += this.source[this.index++];
                    }
                  } else {
                    this.throwUnexpectedToken();
                  }
                }
                if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) {
                  this.throwUnexpectedToken();
                }
                return {
                  type: 6,
                  value: parseFloat(num),
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanStringLiteral = function() {
                var start = this.index;
                var quote = this.source[start];
                assert_1.assert(quote === "'" || quote === '"', "String literal must starts with a quote");
                ++this.index;
                var octal = false;
                var str = "";
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === quote) {
                    quote = "";
                    break;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            str += this.scanUnicodeCodePointEscape();
                          } else {
                            var unescaped_1 = this.scanHexEscape(ch);
                            if (unescaped_1 === null) {
                              this.throwUnexpectedToken();
                            }
                            str += unescaped_1;
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          str += unescaped;
                          break;
                        case "n":
                          str += "\n";
                          break;
                        case "r":
                          str += "\r";
                          break;
                        case "t":
                          str += "	";
                          break;
                        case "b":
                          str += "\b";
                          break;
                        case "f":
                          str += "\f";
                          break;
                        case "v":
                          str += "\v";
                          break;
                        case "8":
                        case "9":
                          str += ch;
                          this.tolerateUnexpectedToken();
                          break;
                        default:
                          if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            var octToDec = this.octalToDecimal(ch);
                            octal = octToDec.octal || octal;
                            str += String.fromCharCode(octToDec.code);
                          } else {
                            str += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    break;
                  } else {
                    str += ch;
                  }
                }
                if (quote !== "") {
                  this.index = start;
                  this.throwUnexpectedToken();
                }
                return {
                  type: 8,
                  value: str,
                  octal,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.scanTemplate = function() {
                var cooked = "";
                var terminated = false;
                var start = this.index;
                var head = this.source[start] === "`";
                var tail = false;
                var rawOffset = 2;
                ++this.index;
                while (!this.eof()) {
                  var ch = this.source[this.index++];
                  if (ch === "`") {
                    rawOffset = 1;
                    tail = true;
                    terminated = true;
                    break;
                  } else if (ch === "$") {
                    if (this.source[this.index] === "{") {
                      this.curlyStack.push("${");
                      ++this.index;
                      terminated = true;
                      break;
                    }
                    cooked += ch;
                  } else if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      switch (ch) {
                        case "n":
                          cooked += "\n";
                          break;
                        case "r":
                          cooked += "\r";
                          break;
                        case "t":
                          cooked += "	";
                          break;
                        case "u":
                          if (this.source[this.index] === "{") {
                            ++this.index;
                            cooked += this.scanUnicodeCodePointEscape();
                          } else {
                            var restore = this.index;
                            var unescaped_2 = this.scanHexEscape(ch);
                            if (unescaped_2 !== null) {
                              cooked += unescaped_2;
                            } else {
                              this.index = restore;
                              cooked += ch;
                            }
                          }
                          break;
                        case "x":
                          var unescaped = this.scanHexEscape(ch);
                          if (unescaped === null) {
                            this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence);
                          }
                          cooked += unescaped;
                          break;
                        case "b":
                          cooked += "\b";
                          break;
                        case "f":
                          cooked += "\f";
                          break;
                        case "v":
                          cooked += "\v";
                          break;
                        default:
                          if (ch === "0") {
                            if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) {
                              this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                            }
                            cooked += "\0";
                          } else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) {
                            this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral);
                          } else {
                            cooked += ch;
                          }
                          break;
                      }
                    } else {
                      ++this.lineNumber;
                      if (ch === "\r" && this.source[this.index] === "\n") {
                        ++this.index;
                      }
                      this.lineStart = this.index;
                    }
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    ++this.lineNumber;
                    if (ch === "\r" && this.source[this.index] === "\n") {
                      ++this.index;
                    }
                    this.lineStart = this.index;
                    cooked += "\n";
                  } else {
                    cooked += ch;
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken();
                }
                if (!head) {
                  this.curlyStack.pop();
                }
                return {
                  type: 10,
                  value: this.source.slice(start + 1, this.index - rawOffset),
                  cooked,
                  head,
                  tail,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.testRegExp = function(pattern, flags) {
                var astralSubstitute = "\uFFFF";
                var tmp = pattern;
                var self = this;
                if (flags.indexOf("u") >= 0) {
                  tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function($0, $1, $2) {
                    var codePoint = parseInt($1 || $2, 16);
                    if (codePoint > 1114111) {
                      self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                    }
                    if (codePoint <= 65535) {
                      return String.fromCharCode(codePoint);
                    }
                    return astralSubstitute;
                  }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute);
                }
                try {
                  RegExp(tmp);
                } catch (e) {
                  this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp);
                }
                try {
                  return new RegExp(pattern, flags);
                } catch (exception) {
                  return null;
                }
              };
              Scanner2.prototype.scanRegExpBody = function() {
                var ch = this.source[this.index];
                assert_1.assert(ch === "/", "Regular expression literal must start with a slash");
                var str = this.source[this.index++];
                var classMarker = false;
                var terminated = false;
                while (!this.eof()) {
                  ch = this.source[this.index++];
                  str += ch;
                  if (ch === "\\") {
                    ch = this.source[this.index++];
                    if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                      this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                    }
                    str += ch;
                  } else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) {
                    this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                  } else if (classMarker) {
                    if (ch === "]") {
                      classMarker = false;
                    }
                  } else {
                    if (ch === "/") {
                      terminated = true;
                      break;
                    } else if (ch === "[") {
                      classMarker = true;
                    }
                  }
                }
                if (!terminated) {
                  this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp);
                }
                return str.substr(1, str.length - 2);
              };
              Scanner2.prototype.scanRegExpFlags = function() {
                var str = "";
                var flags = "";
                while (!this.eof()) {
                  var ch = this.source[this.index];
                  if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) {
                    break;
                  }
                  ++this.index;
                  if (ch === "\\" && !this.eof()) {
                    ch = this.source[this.index];
                    if (ch === "u") {
                      ++this.index;
                      var restore = this.index;
                      var char = this.scanHexEscape("u");
                      if (char !== null) {
                        flags += char;
                        for (str += "\\u"; restore < this.index; ++restore) {
                          str += this.source[restore];
                        }
                      } else {
                        this.index = restore;
                        flags += "u";
                        str += "\\u";
                      }
                      this.tolerateUnexpectedToken();
                    } else {
                      str += "\\";
                      this.tolerateUnexpectedToken();
                    }
                  } else {
                    flags += ch;
                    str += ch;
                  }
                }
                return flags;
              };
              Scanner2.prototype.scanRegExp = function() {
                var start = this.index;
                var pattern = this.scanRegExpBody();
                var flags = this.scanRegExpFlags();
                var value = this.testRegExp(pattern, flags);
                return {
                  type: 9,
                  value: "",
                  pattern,
                  flags,
                  regex: value,
                  lineNumber: this.lineNumber,
                  lineStart: this.lineStart,
                  start,
                  end: this.index
                };
              };
              Scanner2.prototype.lex = function() {
                if (this.eof()) {
                  return {
                    type: 2,
                    value: "",
                    lineNumber: this.lineNumber,
                    lineStart: this.lineStart,
                    start: this.index,
                    end: this.index
                  };
                }
                var cp = this.source.charCodeAt(this.index);
                if (character_1.Character.isIdentifierStart(cp)) {
                  return this.scanIdentifier();
                }
                if (cp === 40 || cp === 41 || cp === 59) {
                  return this.scanPunctuator();
                }
                if (cp === 39 || cp === 34) {
                  return this.scanStringLiteral();
                }
                if (cp === 46) {
                  if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) {
                    return this.scanNumericLiteral();
                  }
                  return this.scanPunctuator();
                }
                if (character_1.Character.isDecimalDigit(cp)) {
                  return this.scanNumericLiteral();
                }
                if (cp === 96 || cp === 125 && this.curlyStack[this.curlyStack.length - 1] === "${") {
                  return this.scanTemplate();
                }
                if (cp >= 55296 && cp < 57343) {
                  if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) {
                    return this.scanIdentifier();
                  }
                }
                return this.scanPunctuator();
              };
              return Scanner2;
            }();
            exports2.Scanner = Scanner;
          },
          /* 13 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            exports2.TokenName = {};
            exports2.TokenName[
              1
              /* BooleanLiteral */
            ] = "Boolean";
            exports2.TokenName[
              2
              /* EOF */
            ] = "<end>";
            exports2.TokenName[
              3
              /* Identifier */
            ] = "Identifier";
            exports2.TokenName[
              4
              /* Keyword */
            ] = "Keyword";
            exports2.TokenName[
              5
              /* NullLiteral */
            ] = "Null";
            exports2.TokenName[
              6
              /* NumericLiteral */
            ] = "Numeric";
            exports2.TokenName[
              7
              /* Punctuator */
            ] = "Punctuator";
            exports2.TokenName[
              8
              /* StringLiteral */
            ] = "String";
            exports2.TokenName[
              9
              /* RegularExpression */
            ] = "RegularExpression";
            exports2.TokenName[
              10
              /* Template */
            ] = "Template";
          },
          /* 14 */
          /***/
          function(module2, exports2) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            exports2.XHTMLEntities = {
              quot: '"',
              amp: "&",
              apos: "'",
              gt: ">",
              nbsp: "\xA0",
              iexcl: "\xA1",
              cent: "\xA2",
              pound: "\xA3",
              curren: "\xA4",
              yen: "\xA5",
              brvbar: "\xA6",
              sect: "\xA7",
              uml: "\xA8",
              copy: "\xA9",
              ordf: "\xAA",
              laquo: "\xAB",
              not: "\xAC",
              shy: "\xAD",
              reg: "\xAE",
              macr: "\xAF",
              deg: "\xB0",
              plusmn: "\xB1",
              sup2: "\xB2",
              sup3: "\xB3",
              acute: "\xB4",
              micro: "\xB5",
              para: "\xB6",
              middot: "\xB7",
              cedil: "\xB8",
              sup1: "\xB9",
              ordm: "\xBA",
              raquo: "\xBB",
              frac14: "\xBC",
              frac12: "\xBD",
              frac34: "\xBE",
              iquest: "\xBF",
              Agrave: "\xC0",
              Aacute: "\xC1",
              Acirc: "\xC2",
              Atilde: "\xC3",
              Auml: "\xC4",
              Aring: "\xC5",
              AElig: "\xC6",
              Ccedil: "\xC7",
              Egrave: "\xC8",
              Eacute: "\xC9",
              Ecirc: "\xCA",
              Euml: "\xCB",
              Igrave: "\xCC",
              Iacute: "\xCD",
              Icirc: "\xCE",
              Iuml: "\xCF",
              ETH: "\xD0",
              Ntilde: "\xD1",
              Ograve: "\xD2",
              Oacute: "\xD3",
              Ocirc: "\xD4",
              Otilde: "\xD5",
              Ouml: "\xD6",
              times: "\xD7",
              Oslash: "\xD8",
              Ugrave: "\xD9",
              Uacute: "\xDA",
              Ucirc: "\xDB",
              Uuml: "\xDC",
              Yacute: "\xDD",
              THORN: "\xDE",
              szlig: "\xDF",
              agrave: "\xE0",
              aacute: "\xE1",
              acirc: "\xE2",
              atilde: "\xE3",
              auml: "\xE4",
              aring: "\xE5",
              aelig: "\xE6",
              ccedil: "\xE7",
              egrave: "\xE8",
              eacute: "\xE9",
              ecirc: "\xEA",
              euml: "\xEB",
              igrave: "\xEC",
              iacute: "\xED",
              icirc: "\xEE",
              iuml: "\xEF",
              eth: "\xF0",
              ntilde: "\xF1",
              ograve: "\xF2",
              oacute: "\xF3",
              ocirc: "\xF4",
              otilde: "\xF5",
              ouml: "\xF6",
              divide: "\xF7",
              oslash: "\xF8",
              ugrave: "\xF9",
              uacute: "\xFA",
              ucirc: "\xFB",
              uuml: "\xFC",
              yacute: "\xFD",
              thorn: "\xFE",
              yuml: "\xFF",
              OElig: "\u0152",
              oelig: "\u0153",
              Scaron: "\u0160",
              scaron: "\u0161",
              Yuml: "\u0178",
              fnof: "\u0192",
              circ: "\u02C6",
              tilde: "\u02DC",
              Alpha: "\u0391",
              Beta: "\u0392",
              Gamma: "\u0393",
              Delta: "\u0394",
              Epsilon: "\u0395",
              Zeta: "\u0396",
              Eta: "\u0397",
              Theta: "\u0398",
              Iota: "\u0399",
              Kappa: "\u039A",
              Lambda: "\u039B",
              Mu: "\u039C",
              Nu: "\u039D",
              Xi: "\u039E",
              Omicron: "\u039F",
              Pi: "\u03A0",
              Rho: "\u03A1",
              Sigma: "\u03A3",
              Tau: "\u03A4",
              Upsilon: "\u03A5",
              Phi: "\u03A6",
              Chi: "\u03A7",
              Psi: "\u03A8",
              Omega: "\u03A9",
              alpha: "\u03B1",
              beta: "\u03B2",
              gamma: "\u03B3",
              delta: "\u03B4",
              epsilon: "\u03B5",
              zeta: "\u03B6",
              eta: "\u03B7",
              theta: "\u03B8",
              iota: "\u03B9",
              kappa: "\u03BA",
              lambda: "\u03BB",
              mu: "\u03BC",
              nu: "\u03BD",
              xi: "\u03BE",
              omicron: "\u03BF",
              pi: "\u03C0",
              rho: "\u03C1",
              sigmaf: "\u03C2",
              sigma: "\u03C3",
              tau: "\u03C4",
              upsilon: "\u03C5",
              phi: "\u03C6",
              chi: "\u03C7",
              psi: "\u03C8",
              omega: "\u03C9",
              thetasym: "\u03D1",
              upsih: "\u03D2",
              piv: "\u03D6",
              ensp: "\u2002",
              emsp: "\u2003",
              thinsp: "\u2009",
              zwnj: "\u200C",
              zwj: "\u200D",
              lrm: "\u200E",
              rlm: "\u200F",
              ndash: "\u2013",
              mdash: "\u2014",
              lsquo: "\u2018",
              rsquo: "\u2019",
              sbquo: "\u201A",
              ldquo: "\u201C",
              rdquo: "\u201D",
              bdquo: "\u201E",
              dagger: "\u2020",
              Dagger: "\u2021",
              bull: "\u2022",
              hellip: "\u2026",
              permil: "\u2030",
              prime: "\u2032",
              Prime: "\u2033",
              lsaquo: "\u2039",
              rsaquo: "\u203A",
              oline: "\u203E",
              frasl: "\u2044",
              euro: "\u20AC",
              image: "\u2111",
              weierp: "\u2118",
              real: "\u211C",
              trade: "\u2122",
              alefsym: "\u2135",
              larr: "\u2190",
              uarr: "\u2191",
              rarr: "\u2192",
              darr: "\u2193",
              harr: "\u2194",
              crarr: "\u21B5",
              lArr: "\u21D0",
              uArr: "\u21D1",
              rArr: "\u21D2",
              dArr: "\u21D3",
              hArr: "\u21D4",
              forall: "\u2200",
              part: "\u2202",
              exist: "\u2203",
              empty: "\u2205",
              nabla: "\u2207",
              isin: "\u2208",
              notin: "\u2209",
              ni: "\u220B",
              prod: "\u220F",
              sum: "\u2211",
              minus: "\u2212",
              lowast: "\u2217",
              radic: "\u221A",
              prop: "\u221D",
              infin: "\u221E",
              ang: "\u2220",
              and: "\u2227",
              or: "\u2228",
              cap: "\u2229",
              cup: "\u222A",
              int: "\u222B",
              there4: "\u2234",
              sim: "\u223C",
              cong: "\u2245",
              asymp: "\u2248",
              ne: "\u2260",
              equiv: "\u2261",
              le: "\u2264",
              ge: "\u2265",
              sub: "\u2282",
              sup: "\u2283",
              nsub: "\u2284",
              sube: "\u2286",
              supe: "\u2287",
              oplus: "\u2295",
              otimes: "\u2297",
              perp: "\u22A5",
              sdot: "\u22C5",
              lceil: "\u2308",
              rceil: "\u2309",
              lfloor: "\u230A",
              rfloor: "\u230B",
              loz: "\u25CA",
              spades: "\u2660",
              clubs: "\u2663",
              hearts: "\u2665",
              diams: "\u2666",
              lang: "\u27E8",
              rang: "\u27E9"
            };
          },
          /* 15 */
          /***/
          function(module2, exports2, __webpack_require__) {
            "use strict";
            Object.defineProperty(exports2, "__esModule", { value: true });
            var error_handler_1 = __webpack_require__(10);
            var scanner_1 = __webpack_require__(12);
            var token_1 = __webpack_require__(13);
            var Reader = function() {
              function Reader2() {
                this.values = [];
                this.curly = this.paren = -1;
              }
              __name(Reader2, "Reader");
              Reader2.prototype.beforeFunctionExpression = function(t2) {
                return [
                  "(",
                  "{",
                  "[",
                  "in",
                  "typeof",
                  "instanceof",
                  "new",
                  "return",
                  "case",
                  "delete",
                  "throw",
                  "void",
                  // assignment operators
                  "=",
                  "+=",
                  "-=",
                  "*=",
                  "**=",
                  "/=",
                  "%=",
                  "<<=",
                  ">>=",
                  ">>>=",
                  "&=",
                  "|=",
                  "^=",
                  ",",
                  // binary/unary operators
                  "+",
                  "-",
                  "*",
                  "**",
                  "/",
                  "%",
                  "++",
                  "--",
                  "<<",
                  ">>",
                  ">>>",
                  "&",
                  "|",
                  "^",
                  "!",
                  "~",
                  "&&",
                  "||",
                  "?",
                  ":",
                  "===",
                  "==",
                  ">=",
                  "<=",
                  "<",
                  ">",
                  "!=",
                  "!=="
                ].indexOf(t2) >= 0;
              };
              Reader2.prototype.isRegexStart = function() {
                var previous = this.values[this.values.length - 1];
                var regex = previous !== null;
                switch (previous) {
                  case "this":
                  case "]":
                    regex = false;
                    break;
                  case ")":
                    var keyword = this.values[this.paren - 1];
                    regex = keyword === "if" || keyword === "while" || keyword === "for" || keyword === "with";
                    break;
                  case "}":
                    regex = false;
                    if (this.values[this.curly - 3] === "function") {
                      var check = this.values[this.curly - 4];
                      regex = check ? !this.beforeFunctionExpression(check) : false;
                    } else if (this.values[this.curly - 4] === "function") {
                      var check = this.values[this.curly - 5];
                      regex = check ? !this.beforeFunctionExpression(check) : true;
                    }
                    break;
                  default:
                    break;
                }
                return regex;
              };
              Reader2.prototype.push = function(token) {
                if (token.type === 7 || token.type === 4) {
                  if (token.value === "{") {
                    this.curly = this.values.length;
                  } else if (token.value === "(") {
                    this.paren = this.values.length;
                  }
                  this.values.push(token.value);
                } else {
                  this.values.push(null);
                }
              };
              return Reader2;
            }();
            var Tokenizer = function() {
              function Tokenizer2(code, config) {
                this.errorHandler = new error_handler_1.ErrorHandler();
                this.errorHandler.tolerant = config ? typeof config.tolerant === "boolean" && config.tolerant : false;
                this.scanner = new scanner_1.Scanner(code, this.errorHandler);
                this.scanner.trackComment = config ? typeof config.comment === "boolean" && config.comment : false;
                this.trackRange = config ? typeof config.range === "boolean" && config.range : false;
                this.trackLoc = config ? typeof config.loc === "boolean" && config.loc : false;
                this.buffer = [];
                this.reader = new Reader();
              }
              __name(Tokenizer2, "Tokenizer");
              Tokenizer2.prototype.errors = function() {
                return this.errorHandler.errors;
              };
              Tokenizer2.prototype.getNextToken = function() {
                if (this.buffer.length === 0) {
                  var comments = this.scanner.scanComments();
                  if (this.scanner.trackComment) {
                    for (var i = 0; i < comments.length; ++i) {
                      var e = comments[i];
                      var value = this.scanner.source.slice(e.slice[0], e.slice[1]);
                      var comment = {
                        type: e.multiLine ? "BlockComment" : "LineComment",
                        value
                      };
                      if (this.trackRange) {
                        comment.range = e.range;
                      }
                      if (this.trackLoc) {
                        comment.loc = e.loc;
                      }
                      this.buffer.push(comment);
                    }
                  }
                  if (!this.scanner.eof()) {
                    var loc = void 0;
                    if (this.trackLoc) {
                      loc = {
                        start: {
                          line: this.scanner.lineNumber,
                          column: this.scanner.index - this.scanner.lineStart
                        },
                        end: {}
                      };
                    }
                    var startRegex = this.scanner.source[this.scanner.index] === "/" && this.reader.isRegexStart();
                    var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex();
                    this.reader.push(token);
                    var entry = {
                      type: token_1.TokenName[token.type],
                      value: this.scanner.source.slice(token.start, token.end)
                    };
                    if (this.trackRange) {
                      entry.range = [token.start, token.end];
                    }
                    if (this.trackLoc) {
                      loc.end = {
                        line: this.scanner.lineNumber,
                        column: this.scanner.index - this.scanner.lineStart
                      };
                      entry.loc = loc;
                    }
                    if (token.type === 9) {
                      var pattern = token.pattern;
                      var flags = token.flags;
                      entry.regex = { pattern, flags };
                    }
                    this.buffer.push(entry);
                  }
                }
                return this.buffer.shift();
              };
              return Tokenizer2;
            }();
            exports2.Tokenizer = Tokenizer;
          }
          /******/
        ])
      );
    });
  }
});

// node_modules/core-util-is/lib/util.js
var require_util = __commonJS({
  "node_modules/core-util-is/lib/util.js"(exports) {
    init_esbuild_shims();
    function isArray(arg) {
      if (Array.isArray) {
        return Array.isArray(arg);
      }
      return objectToString(arg) === "[object Array]";
    }
    __name(isArray, "isArray");
    exports.isArray = isArray;
    function isBoolean(arg) {
      return typeof arg === "boolean";
    }
    __name(isBoolean, "isBoolean");
    exports.isBoolean = isBoolean;
    function isNull(arg) {
      return arg === null;
    }
    __name(isNull, "isNull");
    exports.isNull = isNull;
    function isNullOrUndefined(arg) {
      return arg == null;
    }
    __name(isNullOrUndefined, "isNullOrUndefined");
    exports.isNullOrUndefined = isNullOrUndefined;
    function isNumber(arg) {
      return typeof arg === "number";
    }
    __name(isNumber, "isNumber");
    exports.isNumber = isNumber;
    function isString(arg) {
      return typeof arg === "string";
    }
    __name(isString, "isString");
    exports.isString = isString;
    function isSymbol(arg) {
      return typeof arg === "symbol";
    }
    __name(isSymbol, "isSymbol");
    exports.isSymbol = isSymbol;
    function isUndefined(arg) {
      return arg === void 0;
    }
    __name(isUndefined, "isUndefined");
    exports.isUndefined = isUndefined;
    function isRegExp(re) {
      return objectToString(re) === "[object RegExp]";
    }
    __name(isRegExp, "isRegExp");
    exports.isRegExp = isRegExp;
    function isObject(arg) {
      return typeof arg === "object" && arg !== null;
    }
    __name(isObject, "isObject");
    exports.isObject = isObject;
    function isDate(d) {
      return objectToString(d) === "[object Date]";
    }
    __name(isDate, "isDate");
    exports.isDate = isDate;
    function isError(e) {
      return objectToString(e) === "[object Error]" || e instanceof Error;
    }
    __name(isError, "isError");
    exports.isError = isError;
    function isFunction(arg) {
      return typeof arg === "function";
    }
    __name(isFunction, "isFunction");
    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";
    }
    __name(isPrimitive, "isPrimitive");
    exports.isPrimitive = isPrimitive;
    exports.isBuffer = __require("buffer").Buffer.isBuffer;
    function objectToString(o) {
      return Object.prototype.toString.call(o);
    }
    __name(objectToString, "objectToString");
  }
});

// node_modules/array-timsort/src/index.js
var require_src = __commonJS({
  "node_modules/array-timsort/src/index.js"(exports, module) {
    init_esbuild_shims();
    var DEFAULT_MIN_MERGE = 32;
    var DEFAULT_MIN_GALLOPING = 7;
    var DEFAULT_TMP_STORAGE_LENGTH = 256;
    var POWERS_OF_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9];
    var results;
    var log10 = /* @__PURE__ */ __name((x) => x < 1e5 ? x < 100 ? x < 10 ? 0 : 1 : x < 1e4 ? x < 1e3 ? 2 : 3 : 4 : x < 1e7 ? x < 1e6 ? 5 : 6 : x < 1e9 ? x < 1e8 ? 7 : 8 : 9, "log10");
    function alphabeticalCompare(a, b) {
      if (a === b) {
        return 0;
      }
      if (~~a === a && ~~b === b) {
        if (a === 0 || b === 0) {
          return a < b ? -1 : 1;
        }
        if (a < 0 || b < 0) {
          if (b >= 0) {
            return -1;
          }
          if (a >= 0) {
            return 1;
          }
          a = -a;
          b = -b;
        }
        const al = log10(a);
        const bl = log10(b);
        let t2 = 0;
        if (al < bl) {
          a *= POWERS_OF_TEN[bl - al - 1];
          b /= 10;
          t2 = -1;
        } else if (al > bl) {
          b *= POWERS_OF_TEN[al - bl - 1];
          a /= 10;
          t2 = 1;
        }
        if (a === b) {
          return t2;
        }
        return a < b ? -1 : 1;
      }
      const aStr = String(a);
      const bStr = String(b);
      if (aStr === bStr) {
        return 0;
      }
      return aStr < bStr ? -1 : 1;
    }
    __name(alphabeticalCompare, "alphabeticalCompare");
    function minRunLength(n) {
      let r = 0;
      while (n >= DEFAULT_MIN_MERGE) {
        r |= n & 1;
        n >>= 1;
      }
      return n + r;
    }
    __name(minRunLength, "minRunLength");
    function makeAscendingRun(array, lo, hi, compare) {
      let runHi = lo + 1;
      if (runHi === hi) {
        return 1;
      }
      if (compare(array[runHi++], array[lo]) < 0) {
        while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
          runHi++;
        }
        reverseRun(array, lo, runHi);
        reverseRun(results, lo, runHi);
      } else {
        while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
          runHi++;
        }
      }
      return runHi - lo;
    }
    __name(makeAscendingRun, "makeAscendingRun");
    function reverseRun(array, lo, hi) {
      hi--;
      while (lo < hi) {
        const t2 = array[lo];
        array[lo++] = array[hi];
        array[hi--] = t2;
      }
    }
    __name(reverseRun, "reverseRun");
    function binaryInsertionSort(array, lo, hi, start, compare) {
      if (start === lo) {
        start++;
      }
      for (; start < hi; start++) {
        const pivot = array[start];
        const pivotIndex = results[start];
        let left = lo;
        let right = start;
        while (left < right) {
          const mid = left + right >>> 1;
          if (compare(pivot, array[mid]) < 0) {
            right = mid;
          } else {
            left = mid + 1;
          }
        }
        let n = start - left;
        switch (n) {
          case 3:
            array[left + 3] = array[left + 2];
            results[left + 3] = results[left + 2];
          /* falls through */
          case 2:
            array[left + 2] = array[left + 1];
            results[left + 2] = results[left + 1];
          /* falls through */
          case 1:
            array[left + 1] = array[left];
            results[left + 1] = results[left];
            break;
          default:
            while (n > 0) {
              array[left + n] = array[left + n - 1];
              results[left + n] = results[left + n - 1];
              n--;
            }
        }
        array[left] = pivot;
        results[left] = pivotIndex;
      }
    }
    __name(binaryInsertionSort, "binaryInsertionSort");
    function gallopLeft(value, array, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array[start + hint]) > 0) {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        lastOffset += hint;
        offset += hint;
      } else {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        const tmp = lastOffset;
        lastOffset = hint - offset;
        offset = hint - tmp;
      }
      lastOffset++;
      while (lastOffset < offset) {
        const m = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array[start + m]) > 0) {
          lastOffset = m + 1;
        } else {
          offset = m;
        }
      }
      return offset;
    }
    __name(gallopLeft, "gallopLeft");
    function gallopRight(value, array, start, length, hint, compare) {
      let lastOffset = 0;
      let maxOffset = 0;
      let offset = 1;
      if (compare(value, array[start + hint]) < 0) {
        maxOffset = hint + 1;
        while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        const tmp = lastOffset;
        lastOffset = hint - offset;
        offset = hint - tmp;
      } else {
        maxOffset = length - hint;
        while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
          lastOffset = offset;
          offset = (offset << 1) + 1;
          if (offset <= 0) {
            offset = maxOffset;
          }
        }
        if (offset > maxOffset) {
          offset = maxOffset;
        }
        lastOffset += hint;
        offset += hint;
      }
      lastOffset++;
      while (lastOffset < offset) {
        const m = lastOffset + (offset - lastOffset >>> 1);
        if (compare(value, array[start + m]) < 0) {
          offset = m;
        } else {
          lastOffset = m + 1;
        }
      }
      return offset;
    }
    __name(gallopRight, "gallopRight");
    var TimSort = class {
      static {
        __name(this, "TimSort");
      }
      constructor(array, compare) {
        this.array = array;
        this.compare = compare;
        const { length } = array;
        this.length = length;
        this.minGallop = DEFAULT_MIN_GALLOPING;
        this.tmpStorageLength = length < 2 * DEFAULT_TMP_STORAGE_LENGTH ? length >>> 1 : DEFAULT_TMP_STORAGE_LENGTH;
        this.tmp = new Array(this.tmpStorageLength);
        this.tmpIndex = new Array(this.tmpStorageLength);
        this.stackLength = length < 120 ? 5 : length < 1542 ? 10 : length < 119151 ? 19 : 40;
        this.runStart = new Array(this.stackLength);
        this.runLength = new Array(this.stackLength);
        this.stackSize = 0;
      }
      /**
       * Push a new run on TimSort's stack.
       *
       * @param {number} runStart - Start index of the run in the original array.
       * @param {number} runLength - Length of the run;
       */
      pushRun(runStart, runLength) {
        this.runStart[this.stackSize] = runStart;
        this.runLength[this.stackSize] = runLength;
        this.stackSize += 1;
      }
      /**
       * Merge runs on TimSort's stack so that the following holds for all i:
       * 1) runLength[i - 3] > runLength[i - 2] + runLength[i - 1]
       * 2) runLength[i - 2] > runLength[i - 1]
       */
      mergeRuns() {
        while (this.stackSize > 1) {
          let n = this.stackSize - 2;
          if (n >= 1 && this.runLength[n - 1] <= this.runLength[n] + this.runLength[n + 1] || n >= 2 && this.runLength[n - 2] <= this.runLength[n] + this.runLength[n - 1]) {
            if (this.runLength[n - 1] < this.runLength[n + 1]) {
              n--;
            }
          } else if (this.runLength[n] > this.runLength[n + 1]) {
            break;
          }
          this.mergeAt(n);
        }
      }
      /**
       * Merge all runs on TimSort's stack until only one remains.
       */
      forceMergeRuns() {
        while (this.stackSize > 1) {
          let n = this.stackSize - 2;
          if (n > 0 && this.runLength[n - 1] < this.runLength[n + 1]) {
            n--;
          }
          this.mergeAt(n);
        }
      }
      /**
       * Merge the runs on the stack at positions i and i+1. Must be always be called
       * with i=stackSize-2 or i=stackSize-3 (that is, we merge on top of the stack).
       *
       * @param {number} i - Index of the run to merge in TimSort's stack.
       */
      mergeAt(i) {
        const { compare } = this;
        const { array } = this;
        let start1 = this.runStart[i];
        let length1 = this.runLength[i];
        const start2 = this.runStart[i + 1];
        let length2 = this.runLength[i + 1];
        this.runLength[i] = length1 + length2;
        if (i === this.stackSize - 3) {
          this.runStart[i + 1] = this.runStart[i + 2];
          this.runLength[i + 1] = this.runLength[i + 2];
        }
        this.stackSize--;
        const k = gallopRight(array[start2], array, start1, length1, 0, compare);
        start1 += k;
        length1 -= k;
        if (length1 === 0) {
          return;
        }
        length2 = gallopLeft(
          array[start1 + length1 - 1],
          array,
          start2,
          length2,
          length2 - 1,
          compare
        );
        if (length2 === 0) {
          return;
        }
        if (length1 <= length2) {
          this.mergeLow(start1, length1, start2, length2);
        } else {
          this.mergeHigh(start1, length1, start2, length2);
        }
      }
      /**
       * Merge two adjacent runs in a stable way. The runs must be such that the
       * first element of run1 is bigger than the first element in run2 and the
       * last element of run1 is greater than all the elements in run2.
       * The method should be called when run1.length <= run2.length as it uses
       * TimSort temporary array to store run1. Use mergeHigh if run1.length >
       * run2.length.
       *
       * @param {number} start1 - First element in run1.
       * @param {number} length1 - Length of run1.
       * @param {number} start2 - First element in run2.
       * @param {number} length2 - Length of run2.
       */
      mergeLow(start1, length1, start2, length2) {
        const { compare } = this;
        const { array } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i = 0;
        for (i = 0; i < length1; i++) {
          tmp[i] = array[start1 + i];
          tmpIndex[i] = results[start1 + i];
        }
        let cursor1 = 0;
        let cursor2 = start2;
        let dest = start1;
        array[dest] = array[cursor2];
        results[dest] = results[cursor2];
        dest++;
        cursor2++;
        if (--length2 === 0) {
          for (i = 0; i < length1; i++) {
            array[dest + i] = tmp[cursor1 + i];
            results[dest + i] = tmpIndex[cursor1 + i];
          }
          return;
        }
        if (length1 === 1) {
          for (i = 0; i < length2; i++) {
            array[dest + i] = array[cursor2 + i];
            results[dest + i] = results[cursor2 + i];
          }
          array[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
          return;
        }
        let { minGallop } = this;
        while (true) {
          let count1 = 0;
          let count2 = 0;
          let exit = false;
          do {
            if (compare(array[cursor2], tmp[cursor1]) < 0) {
              array[dest] = array[cursor2];
              results[dest] = results[cursor2];
              dest++;
              cursor2++;
              count2++;
              count1 = 0;
              if (--length2 === 0) {
                exit = true;
                break;
              }
            } else {
              array[dest] = tmp[cursor1];
              results[dest] = tmpIndex[cursor1];
              dest++;
              cursor1++;
              count1++;
              count2 = 0;
              if (--length1 === 1) {
                exit = true;
                break;
              }
            }
          } while ((count1 | count2) < minGallop);
          if (exit) {
            break;
          }
          do {
            count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
            if (count1 !== 0) {
              for (i = 0; i < count1; i++) {
                array[dest + i] = tmp[cursor1 + i];
                results[dest + i] = tmpIndex[cursor1 + i];
              }
              dest += count1;
              cursor1 += count1;
              length1 -= count1;
              if (length1 <= 1) {
                exit = true;
                break;
              }
            }
            array[dest] = array[cursor2];
            results[dest] = results[cursor2];
            dest++;
            cursor2++;
            if (--length2 === 0) {
              exit = true;
              break;
            }
            count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
            if (count2 !== 0) {
              for (i = 0; i < count2; i++) {
                array[dest + i] = array[cursor2 + i];
                results[dest + i] = results[cursor2 + i];
              }
              dest += count2;
              cursor2 += count2;
              length2 -= count2;
              if (length2 === 0) {
                exit = true;
                break;
              }
            }
            array[dest] = tmp[cursor1];
            results[dest] = tmpIndex[cursor1];
            dest++;
            cursor1++;
            if (--length1 === 1) {
              exit = true;
              break;
            }
            minGallop--;
          } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
          if (exit) {
            break;
          }
          if (minGallop < 0) {
            minGallop = 0;
          }
          minGallop += 2;
        }
        this.minGallop = minGallop;
        if (minGallop < 1) {
          this.minGallop = 1;
        }
        if (length1 === 1) {
          for (i = 0; i < length2; i++) {
            array[dest + i] = array[cursor2 + i];
            results[dest + i] = results[cursor2 + i];
          }
          array[dest + length2] = tmp[cursor1];
          results[dest + length2] = tmpIndex[cursor1];
        } else if (length1 === 0) {
          throw new Error("mergeLow preconditions were not respected");
        } else {
          for (i = 0; i < length1; i++) {
            array[dest + i] = tmp[cursor1 + i];
            results[dest + i] = tmpIndex[cursor1 + i];
          }
        }
      }
      /**
       * Merge two adjacent runs in a stable way. The runs must be such that the
       * first element of run1 is bigger than the first element in run2 and the
       * last element of run1 is greater than all the elements in run2.
       * The method should be called when run1.length > run2.length as it uses
       * TimSort temporary array to store run2. Use mergeLow if run1.length <=
       * run2.length.
       *
       * @param {number} start1 - First element in run1.
       * @param {number} length1 - Length of run1.
       * @param {number} start2 - First element in run2.
       * @param {number} length2 - Length of run2.
       */
      mergeHigh(start1, length1, start2, length2) {
        const { compare } = this;
        const { array } = this;
        const { tmp } = this;
        const { tmpIndex } = this;
        let i = 0;
        for (i = 0; i < length2; i++) {
          tmp[i] = array[start2 + i];
          tmpIndex[i] = results[start2 + i];
        }
        let cursor1 = start1 + length1 - 1;
        let cursor2 = length2 - 1;
        let dest = start2 + length2 - 1;
        let customCursor = 0;
        let customDest = 0;
        array[dest] = array[cursor1];
        results[dest] = results[cursor1];
        dest--;
        cursor1--;
        if (--length1 === 0) {
          customCursor = dest - (length2 - 1);
          for (i = 0; i < length2; i++) {
            array[customCursor + i] = tmp[i];
            results[customCursor + i] = tmpIndex[i];
          }
          return;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i = length1 - 1; i >= 0; i--) {
            array[customDest + i] = array[customCursor + i];
            results[customDest + i] = results[customCursor + i];
          }
          array[dest] = tmp[cursor2];
          results[dest] = tmpIndex[cursor2];
          return;
        }
        let { minGallop } = this;
        while (true) {
          let count1 = 0;
          let count2 = 0;
          let exit = false;
          do {
            if (compare(tmp[cursor2], array[cursor1]) < 0) {
              array[dest] = array[cursor1];
              results[dest] = results[cursor1];
              dest--;
              cursor1--;
              count1++;
              count2 = 0;
              if (--length1 === 0) {
                exit = true;
                break;
              }
            } else {
              array[dest] = tmp[cursor2];
              results[dest] = tmpIndex[cursor2];
              dest--;
              cursor2--;
              count2++;
              count1 = 0;
              if (--length2 === 1) {
                exit = true;
                break;
              }
            }
          } while ((count1 | count2) < minGallop);
          if (exit) {
            break;
          }
          do {
            count1 = length1 - gallopRight(
              tmp[cursor2],
              array,
              start1,
              length1,
              length1 - 1,
              compare
            );
            if (count1 !== 0) {
              dest -= count1;
              cursor1 -= count1;
              length1 -= count1;
              customDest = dest + 1;
              customCursor = cursor1 + 1;
              for (i = count1 - 1; i >= 0; i--) {
                array[customDest + i] = array[customCursor + i];
                results[customDest + i] = results[customCursor + i];
              }
              if (length1 === 0) {
                exit = true;
                break;
              }
            }
            array[dest] = tmp[cursor2];
            results[dest] = tmpIndex[cursor2];
            dest--;
            cursor2--;
            if (--length2 === 1) {
              exit = true;
              break;
            }
            count2 = length2 - gallopLeft(
              array[cursor1],
              tmp,
              0,
              length2,
              length2 - 1,
              compare
            );
            if (count2 !== 0) {
              dest -= count2;
              cursor2 -= count2;
              length2 -= count2;
              customDest = dest + 1;
              customCursor = cursor2 + 1;
              for (i = 0; i < count2; i++) {
                array[customDest + i] = tmp[customCursor + i];
                results[customDest + i] = tmpIndex[customCursor + i];
              }
              if (length2 <= 1) {
                exit = true;
                break;
              }
            }
            array[dest] = array[cursor1];
            results[dest] = results[cursor1];
            dest--;
            cursor1--;
            if (--length1 === 0) {
              exit = true;
              break;
            }
            minGallop--;
          } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
          if (exit) {
            break;
          }
          if (minGallop < 0) {
            minGallop = 0;
          }
          minGallop += 2;
        }
        this.minGallop = minGallop;
        if (minGallop < 1) {
          this.minGallop = 1;
        }
        if (length2 === 1) {
          dest -= length1;
          cursor1 -= length1;
          customDest = dest + 1;
          customCursor = cursor1 + 1;
          for (i = length1 - 1; i >= 0; i--) {
            array[customDest + i] = array[customCursor + i];
            results[customDest + i] = results[customCursor + i];
          }
          array[dest] = tmp[cursor2];
          results[dest] = tmpIndex[cursor2];
        } else if (length2 === 0) {
          throw new Error("mergeHigh preconditions were not respected");
        } else {
          customCursor = dest - (length2 - 1);
          for (i = 0; i < length2; i++) {
            array[customCursor + i] = tmp[i];
            results[customCursor + i] = tmpIndex[i];
          }
        }
      }
    };
    function sort(array, compare, lo, hi) {
      if (!Array.isArray(array)) {
        throw new TypeError(
          `The "array" argument must be an array. Received ${array}`
        );
      }
      results = [];
      const { length } = array;
      let i = 0;
      while (i < length) {
        results[i] = i++;
      }
      if (!compare) {
        compare = alphabeticalCompare;
      } else if (typeof compare !== "function") {
        hi = lo;
        lo = compare;
        compare = alphabeticalCompare;
      }
      if (!lo) {
        lo = 0;
      }
      if (!hi) {
        hi = length;
      }
      let remaining = hi - lo;
      if (remaining < 2) {
        return results;
      }
      let runLength = 0;
      if (remaining < DEFAULT_MIN_MERGE) {
        runLength = makeAscendingRun(array, lo, hi, compare);
        binaryInsertionSort(array, lo, hi, lo + runLength, compare);
        return results;
      }
      const ts = new TimSort(array, compare);
      const minRun = minRunLength(remaining);
      do {
        runLength = makeAscendingRun(array, lo, hi, compare);
        if (runLength < minRun) {
          let force = remaining;
          if (force > minRun) {
            force = minRun;
          }
          binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
          runLength = force;
        }
        ts.pushRun(lo, runLength);
        ts.mergeRuns();
        remaining -= runLength;
        lo += runLength;
      } while (remaining !== 0);
      ts.forceMergeRuns();
      return results;
    }
    __name(sort, "sort");
    module.exports = {
      sort
    };
  }
});

// node_modules/has-own-prop/index.js
var require_has_own_prop = __commonJS({
  "node_modules/has-own-prop/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var hasOwnProp = Object.prototype.hasOwnProperty;
    module.exports = (object, property) => hasOwnProp.call(object, property);
  }
});

// node_modules/comment-json/src/common.js
var require_common = __commonJS({
  "node_modules/comment-json/src/common.js"(exports, module) {
    init_esbuild_shims();
    var hasOwnProperty = require_has_own_prop();
    var {
      isObject,
      isArray,
      isString,
      isNumber
    } = require_util();
    var PREFIX_BEFORE = "before";
    var PREFIX_AFTER_PROP = "after-prop";
    var PREFIX_AFTER_COLON = "after-colon";
    var PREFIX_AFTER_VALUE = "after-value";
    var PREFIX_AFTER = "after";
    var PREFIX_BEFORE_ALL = "before-all";
    var PREFIX_AFTER_ALL = "after-all";
    var BRACKET_OPEN = "[";
    var BRACKET_CLOSE = "]";
    var CURLY_BRACKET_OPEN = "{";
    var CURLY_BRACKET_CLOSE = "}";
    var COMMA = ",";
    var EMPTY = "";
    var MINUS = "-";
    var SYMBOL_PREFIXES = [
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER
    ];
    var NON_PROP_SYMBOL_KEYS = [
      PREFIX_BEFORE,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL
    ].map(Symbol.for);
    var COLON = ":";
    var UNDEFINED = void 0;
    var symbol = /* @__PURE__ */ __name((prefix, key) => Symbol.for(prefix + COLON + key), "symbol");
    var define2 = /* @__PURE__ */ __name((target, key, value) => Object.defineProperty(target, key, {
      value,
      writable: true,
      configurable: true
    }), "define");
    var copy_comments_by_kind = /* @__PURE__ */ __name((target, source, target_key, source_key, prefix, remove_source) => {
      const source_prop = symbol(prefix, source_key);
      if (!hasOwnProperty(source, source_prop)) {
        return;
      }
      const target_prop = target_key === source_key ? source_prop : symbol(prefix, target_key);
      define2(target, target_prop, source[source_prop]);
      if (remove_source) {
        delete source[source_prop];
      }
    }, "copy_comments_by_kind");
    var copy_comments = /* @__PURE__ */ __name((target, source, target_key, source_key, remove_source) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        copy_comments_by_kind(
          target,
          source,
          target_key,
          source_key,
          prefix,
          remove_source
        );
      });
    }, "copy_comments");
    var swap_comments = /* @__PURE__ */ __name((array, from, to) => {
      if (from === to) {
        return;
      }
      SYMBOL_PREFIXES.forEach((prefix) => {
        const target_prop = symbol(prefix, to);
        if (!hasOwnProperty(array, target_prop)) {
          copy_comments_by_kind(array, array, to, from, prefix, true);
          return;
        }
        const comments = array[target_prop];
        delete array[target_prop];
        copy_comments_by_kind(array, array, to, from, prefix, true);
        define2(array, symbol(prefix, from), comments);
      });
    }, "swap_comments");
    var assign_non_prop_comments = /* @__PURE__ */ __name((target, source) => {
      NON_PROP_SYMBOL_KEYS.forEach((key) => {
        const comments = source[key];
        if (comments) {
          define2(target, key, comments);
        }
      });
    }, "assign_non_prop_comments");
    var assign = /* @__PURE__ */ __name((target, source, keys) => {
      keys.forEach((key) => {
        if (!isString(key) && !isNumber(key)) {
          return;
        }
        if (!hasOwnProperty(source, key)) {
          return;
        }
        target[key] = source[key];
        copy_comments(target, source, key, key);
      });
      return target;
    }, "assign");
    module.exports = {
      SYMBOL_PREFIXES,
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      MINUS,
      EMPTY,
      UNDEFINED,
      symbol,
      define: define2,
      copy_comments,
      swap_comments,
      assign_non_prop_comments,
      assign(target, source, keys) {
        if (!isObject(target)) {
          throw new TypeError("Cannot convert undefined or null to object");
        }
        if (!isObject(source)) {
          return target;
        }
        if (keys === UNDEFINED) {
          keys = Object.keys(source);
          assign_non_prop_comments(target, source);
        } else if (!isArray(keys)) {
          throw new TypeError("keys must be array or undefined");
        } else if (keys.length === 0) {
          assign_non_prop_comments(target, source);
        }
        return assign(target, source, keys);
      }
    };
  }
});

// node_modules/comment-json/src/array.js
var require_array = __commonJS({
  "node_modules/comment-json/src/array.js"(exports, module) {
    init_esbuild_shims();
    var { isArray } = require_util();
    var { sort } = require_src();
    var {
      SYMBOL_PREFIXES,
      UNDEFINED,
      symbol,
      copy_comments,
      swap_comments
    } = require_common();
    var reverse_comments = /* @__PURE__ */ __name((array) => {
      const { length } = array;
      let i = 0;
      const max = length / 2;
      for (; i < max; i++) {
        swap_comments(array, i, length - i - 1);
      }
    }, "reverse_comments");
    var move_comment = /* @__PURE__ */ __name((target, source, i, offset, remove) => {
      copy_comments(target, source, i + offset, i, remove);
    }, "move_comment");
    var move_comments = /* @__PURE__ */ __name((target, source, start, count, offset, remove) => {
      if (offset > 0) {
        let i2 = count;
        while (i2-- > 0) {
          move_comment(target, source, start + i2, offset, remove);
        }
        return;
      }
      let i = 0;
      while (i < count) {
        const ii = i++;
        move_comment(target, source, start + ii, offset, remove);
      }
    }, "move_comments");
    var remove_comments = /* @__PURE__ */ __name((array, key) => {
      SYMBOL_PREFIXES.forEach((prefix) => {
        const prop = symbol(prefix, key);
        delete array[prop];
      });
    }, "remove_comments");
    var get_mapped = /* @__PURE__ */ __name((map, key) => {
      let mapped = key;
      while (mapped in map) {
        mapped = map[mapped];
      }
      return mapped;
    }, "get_mapped");
    var CommentArray = class _CommentArray extends Array {
      static {
        __name(this, "CommentArray");
      }
      // - deleteCount + items.length
      // We should avoid `splice(begin, deleteCount, ...items)`,
      // because `splice(0, undefined)` is not equivalent to `splice(0)`,
      // as well as:
      // - slice
      splice(...args) {
        const { length } = this;
        const ret = super.splice(...args);
        let [begin, deleteCount, ...items] = args;
        if (begin < 0) {
          begin += length;
        }
        if (arguments.length === 1) {
          deleteCount = length - begin;
        } else {
          deleteCount = Math.min(length - begin, deleteCount);
        }
        const {
          length: item_length
        } = items;
        const offset = item_length - deleteCount;
        const start = begin + deleteCount;
        const count = length - start;
        move_comments(this, this, start, count, offset, true);
        return ret;
      }
      slice(...args) {
        const { length } = this;
        const array = super.slice(...args);
        if (!array.length) {
          return new _CommentArray();
        }
        let [begin, before] = args;
        if (before === UNDEFINED) {
          before = length;
        } else if (before < 0) {
          before += length;
        }
        if (begin < 0) {
          begin += length;
        } else if (begin === UNDEFINED) {
          begin = 0;
        }
        move_comments(array, this, begin, before - begin, -begin);
        return array;
      }
      unshift(...items) {
        const { length } = this;
        const ret = super.unshift(...items);
        const {
          length: items_length
        } = items;
        if (items_length > 0) {
          move_comments(this, this, 0, length, items_length, true);
        }
        return ret;
      }
      shift() {
        const ret = super.shift();
        const { length } = this;
        remove_comments(this, 0);
        move_comments(this, this, 1, length, -1, true);
        return ret;
      }
      reverse() {
        super.reverse();
        reverse_comments(this);
        return this;
      }
      pop() {
        const ret = super.pop();
        remove_comments(this, this.length);
        return ret;
      }
      concat(...items) {
        let { length } = this;
        const ret = super.concat(...items);
        if (!items.length) {
          return ret;
        }
        move_comments(ret, this, 0, this.length, 0);
        items.forEach((item) => {
          const prev = length;
          length += isArray(item) ? item.length : 1;
          if (!(item instanceof _CommentArray)) {
            return;
          }
          move_comments(ret, item, 0, item.length, prev);
        });
        return ret;
      }
      sort(...args) {
        const result = sort(
          this,
          ...args.slice(0, 1)
        );
        const map = /* @__PURE__ */ Object.create(null);
        result.forEach((source_index, index) => {
          if (source_index === index) {
            return;
          }
          const real_source_index = get_mapped(map, source_index);
          if (real_source_index === index) {
            return;
          }
          map[index] = real_source_index;
          swap_comments(this, index, real_source_index);
        });
        return this;
      }
    };
    module.exports = {
      CommentArray
    };
  }
});

// node_modules/comment-json/src/parse.js
var require_parse = __commonJS({
  "node_modules/comment-json/src/parse.js"(exports, module) {
    init_esbuild_shims();
    var esprima = require_esprima();
    var {
      CommentArray
    } = require_array();
    var {
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_BEFORE_ALL,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      MINUS,
      EMPTY,
      UNDEFINED,
      define: define2,
      assign_non_prop_comments
    } = require_common();
    var tokenize = /* @__PURE__ */ __name((code) => esprima.tokenize(code, {
      comment: true,
      loc: true
    }), "tokenize");
    var previous_hosts = [];
    var comments_host = null;
    var unassigned_comments = null;
    var previous_props = [];
    var last_prop;
    var remove_comments = false;
    var inline = false;
    var tokens = null;
    var last = null;
    var current = null;
    var index;
    var reviver = null;
    var clean = /* @__PURE__ */ __name(() => {
      previous_props.length = previous_hosts.length = 0;
      last = null;
      last_prop = UNDEFINED;
    }, "clean");
    var free = /* @__PURE__ */ __name(() => {
      clean();
      tokens.length = 0;
      unassigned_comments = comments_host = tokens = last = current = reviver = null;
    }, "free");
    var symbolFor = /* @__PURE__ */ __name((prefix) => Symbol.for(
      last_prop !== UNDEFINED ? prefix + COLON + last_prop : prefix
    ), "symbolFor");
    var transform = /* @__PURE__ */ __name((k, v) => reviver ? reviver(k, v) : v, "transform");
    var unexpected = /* @__PURE__ */ __name(() => {
      const error = new SyntaxError(`Unexpected token ${current.value.slice(0, 1)}`);
      Object.assign(error, current.loc.start);
      throw error;
    }, "unexpected");
    var unexpected_end = /* @__PURE__ */ __name(() => {
      const error = new SyntaxError("Unexpected end of JSON input");
      Object.assign(error, last ? last.loc.end : {
        line: 1,
        column: 0
      });
      throw error;
    }, "unexpected_end");
    var next = /* @__PURE__ */ __name(() => {
      const new_token = tokens[++index];
      inline = current && new_token && current.loc.end.line === new_token.loc.start.line || false;
      last = current;
      current = new_token;
    }, "next");
    var type = /* @__PURE__ */ __name(() => {
      if (!current) {
        unexpected_end();
      }
      return current.type === "Punctuator" ? current.value : current.type;
    }, "type");
    var is = /* @__PURE__ */ __name((t2) => type() === t2, "is");
    var expect = /* @__PURE__ */ __name((a) => {
      if (!is(a)) {
        unexpected();
      }
    }, "expect");
    var set_comments_host = /* @__PURE__ */ __name((new_host) => {
      previous_hosts.push(comments_host);
      comments_host = new_host;
    }, "set_comments_host");
    var restore_comments_host = /* @__PURE__ */ __name(() => {
      comments_host = previous_hosts.pop();
    }, "restore_comments_host");
    var assign_after_comments = /* @__PURE__ */ __name(() => {
      if (!unassigned_comments) {
        return;
      }
      const after_comments = [];
      for (const comment of unassigned_comments) {
        if (comment.inline) {
          after_comments.push(comment);
        } else {
          break;
        }
      }
      const { length } = after_comments;
      if (!length) {
        return;
      }
      if (length === unassigned_comments.length) {
        unassigned_comments = null;
      } else {
        unassigned_comments.splice(0, length);
      }
      define2(comments_host, symbolFor(PREFIX_AFTER), after_comments);
    }, "assign_after_comments");
    var assign_comments = /* @__PURE__ */ __name((prefix) => {
      if (!unassigned_comments) {
        return;
      }
      define2(comments_host, symbolFor(prefix), unassigned_comments);
      unassigned_comments = null;
    }, "assign_comments");
    var parse_comments = /* @__PURE__ */ __name((prefix) => {
      const comments = [];
      while (current && (is("LineComment") || is("BlockComment"))) {
        const comment = {
          ...current,
          inline
        };
        comments.push(comment);
        next();
      }
      if (remove_comments) {
        return;
      }
      if (!comments.length) {
        return;
      }
      if (prefix) {
        define2(comments_host, symbolFor(prefix), comments);
        return;
      }
      unassigned_comments = comments;
    }, "parse_comments");
    var set_prop = /* @__PURE__ */ __name((prop, push) => {
      if (push) {
        previous_props.push(last_prop);
      }
      last_prop = prop;
    }, "set_prop");
    var restore_prop = /* @__PURE__ */ __name(() => {
      last_prop = previous_props.pop();
    }, "restore_prop");
    var parse_object = /* @__PURE__ */ __name(() => {
      const obj = {};
      set_comments_host(obj);
      set_prop(UNDEFINED, true);
      let started = false;
      let name;
      parse_comments();
      while (!is(CURLY_BRACKET_CLOSE)) {
        if (started) {
          assign_comments(PREFIX_AFTER_VALUE);
          expect(COMMA);
          next();
          parse_comments();
          assign_after_comments();
          if (is(CURLY_BRACKET_CLOSE)) {
            break;
          }
        }
        started = true;
        expect("String");
        name = JSON.parse(current.value);
        set_prop(name);
        assign_comments(PREFIX_BEFORE);
        next();
        parse_comments(PREFIX_AFTER_PROP);
        expect(COLON);
        next();
        parse_comments(PREFIX_AFTER_COLON);
        obj[name] = transform(name, walk());
        parse_comments();
      }
      if (started) {
        assign_comments(PREFIX_AFTER);
      }
      next();
      last_prop = void 0;
      if (!started) {
        assign_comments(PREFIX_BEFORE);
      }
      restore_comments_host();
      restore_prop();
      return obj;
    }, "parse_object");
    var parse_array = /* @__PURE__ */ __name(() => {
      const array = new CommentArray();
      set_comments_host(array);
      set_prop(UNDEFINED, true);
      let started = false;
      let i = 0;
      parse_comments();
      while (!is(BRACKET_CLOSE)) {
        if (started) {
          assign_comments(PREFIX_AFTER_VALUE);
          expect(COMMA);
          next();
          parse_comments();
          assign_after_comments();
          if (is(BRACKET_CLOSE)) {
            break;
          }
        }
        started = true;
        set_prop(i);
        assign_comments(PREFIX_BEFORE);
        array[i] = transform(i, walk());
        i++;
        parse_comments();
      }
      if (started) {
        assign_comments(PREFIX_AFTER);
      }
      next();
      last_prop = void 0;
      if (!started) {
        assign_comments(PREFIX_BEFORE);
      }
      restore_comments_host();
      restore_prop();
      return array;
    }, "parse_array");
    function walk() {
      let tt = type();
      if (tt === CURLY_BRACKET_OPEN) {
        next();
        return parse_object();
      }
      if (tt === BRACKET_OPEN) {
        next();
        return parse_array();
      }
      let negative = EMPTY;
      if (tt === MINUS) {
        next();
        tt = type();
        negative = MINUS;
      }
      let v;
      switch (tt) {
        case "String":
        case "Boolean":
        case "Null":
        case "Numeric":
          v = current.value;
          next();
          return JSON.parse(negative + v);
        default:
      }
    }
    __name(walk, "walk");
    var isObject = /* @__PURE__ */ __name((subject) => Object(subject) === subject, "isObject");
    var parse4 = /* @__PURE__ */ __name((code, rev, no_comments) => {
      clean();
      tokens = tokenize(code);
      reviver = rev;
      remove_comments = no_comments;
      if (!tokens.length) {
        unexpected_end();
      }
      index = -1;
      next();
      set_comments_host({});
      parse_comments(PREFIX_BEFORE_ALL);
      let result = walk();
      parse_comments(PREFIX_AFTER_ALL);
      if (current) {
        unexpected();
      }
      if (!no_comments && result !== null) {
        if (!isObject(result)) {
          result = new Object(result);
        }
        assign_non_prop_comments(result, comments_host);
      }
      restore_comments_host();
      result = transform("", result);
      free();
      return result;
    }, "parse");
    module.exports = {
      parse: parse4,
      tokenize
    };
  }
});

// node_modules/repeat-string/index.js
var require_repeat_string = __commonJS({
  "node_modules/repeat-string/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var res = "";
    var cache;
    module.exports = repeat;
    function repeat(str, num) {
      if (typeof str !== "string") {
        throw new TypeError("expected a string");
      }
      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;
    }
    __name(repeat, "repeat");
  }
});

// node_modules/comment-json/src/stringify.js
var require_stringify = __commonJS({
  "node_modules/comment-json/src/stringify.js"(exports, module) {
    init_esbuild_shims();
    var {
      isArray,
      isObject,
      isFunction,
      isNumber,
      isString
    } = require_util();
    var repeat = require_repeat_string();
    var {
      PREFIX_BEFORE_ALL,
      PREFIX_BEFORE,
      PREFIX_AFTER_PROP,
      PREFIX_AFTER_COLON,
      PREFIX_AFTER_VALUE,
      PREFIX_AFTER,
      PREFIX_AFTER_ALL,
      BRACKET_OPEN,
      BRACKET_CLOSE,
      CURLY_BRACKET_OPEN,
      CURLY_BRACKET_CLOSE,
      COLON,
      COMMA,
      EMPTY,
      UNDEFINED
    } = require_common();
    var ESCAPABLE = /[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var SPACE = " ";
    var LF = "\n";
    var STR_NULL = "null";
    var BEFORE = /* @__PURE__ */ __name((prop) => `${PREFIX_BEFORE}:${prop}`, "BEFORE");
    var AFTER_PROP = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_PROP}:${prop}`, "AFTER_PROP");
    var AFTER_COLON = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_COLON}:${prop}`, "AFTER_COLON");
    var AFTER_VALUE = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER_VALUE}:${prop}`, "AFTER_VALUE");
    var AFTER = /* @__PURE__ */ __name((prop) => `${PREFIX_AFTER}:${prop}`, "AFTER");
    var meta = {
      "\b": "\\b",
      "	": "\\t",
      "\n": "\\n",
      "\f": "\\f",
      "\r": "\\r",
      '"': '\\"',
      "\\": "\\\\"
    };
    var escape = /* @__PURE__ */ __name((string) => {
      ESCAPABLE.lastIndex = 0;
      if (!ESCAPABLE.test(string)) {
        return string;
      }
      return string.replace(ESCAPABLE, (a) => {
        const c = meta[a];
        return typeof c === "string" ? c : a;
      });
    }, "escape");
    var quote = /* @__PURE__ */ __name((string) => `"${escape(string)}"`, "quote");
    var comment_stringify = /* @__PURE__ */ __name((value, line) => line ? `//${value}` : `/*${value}*/`, "comment_stringify");
    var process_comments = /* @__PURE__ */ __name((host, symbol_tag, deeper_gap, display_block) => {
      const comments = host[Symbol.for(symbol_tag)];
      if (!comments || !comments.length) {
        return EMPTY;
      }
      let is_line_comment = false;
      const str = comments.reduce((prev, {
        inline,
        type,
        value
      }) => {
        const delimiter = inline ? SPACE : LF + deeper_gap;
        is_line_comment = type === "LineComment";
        return prev + delimiter + comment_stringify(value, is_line_comment);
      }, EMPTY);
      return display_block || is_line_comment ? str + LF + deeper_gap : str;
    }, "process_comments");
    var replacer = null;
    var indent = EMPTY;
    var clean = /* @__PURE__ */ __name(() => {
      replacer = null;
      indent = EMPTY;
    }, "clean");
    var join4 = /* @__PURE__ */ __name((one, two, gap) => one ? two ? one + two.trim() + LF + gap : one.trimRight() + LF + gap : two ? two.trimRight() + LF + gap : EMPTY, "join");
    var join_content = /* @__PURE__ */ __name((inside, value, gap) => {
      const comment = process_comments(value, PREFIX_BEFORE, gap + indent, true);
      return join4(comment, inside, gap);
    }, "join_content");
    var array_stringify = /* @__PURE__ */ __name((value, gap) => {
      const deeper_gap = gap + indent;
      const { length } = value;
      let inside = EMPTY;
      let after_comma = EMPTY;
      for (let i = 0; i < length; i++) {
        if (i !== 0) {
          inside += COMMA;
        }
        const before = join4(
          after_comma,
          process_comments(value, BEFORE(i), deeper_gap),
          deeper_gap
        );
        inside += before || LF + deeper_gap;
        inside += stringify3(i, value, deeper_gap) || STR_NULL;
        inside += process_comments(value, AFTER_VALUE(i), deeper_gap);
        after_comma = process_comments(value, AFTER(i), deeper_gap);
      }
      inside += join4(
        after_comma,
        process_comments(value, PREFIX_AFTER, deeper_gap),
        deeper_gap
      );
      return BRACKET_OPEN + join_content(inside, value, gap) + BRACKET_CLOSE;
    }, "array_stringify");
    var object_stringify = /* @__PURE__ */ __name((value, gap) => {
      if (!value) {
        return "null";
      }
      const deeper_gap = gap + indent;
      let inside = EMPTY;
      let after_comma = EMPTY;
      let first = true;
      const keys = isArray(replacer) ? replacer : Object.keys(value);
      const iteratee = /* @__PURE__ */ __name((key) => {
        const sv = stringify3(key, value, deeper_gap);
        if (sv === UNDEFINED) {
          return;
        }
        if (!first) {
          inside += COMMA;
        }
        first = false;
        const before = join4(
          after_comma,
          process_comments(value, BEFORE(key), deeper_gap),
          deeper_gap
        );
        inside += before || LF + deeper_gap;
        inside += quote(key) + process_comments(value, AFTER_PROP(key), deeper_gap) + COLON + process_comments(value, AFTER_COLON(key), deeper_gap) + SPACE + sv + process_comments(value, AFTER_VALUE(key), deeper_gap);
        after_comma = process_comments(value, AFTER(key), deeper_gap);
      }, "iteratee");
      keys.forEach(iteratee);
      inside += join4(
        after_comma,
        process_comments(value, PREFIX_AFTER, deeper_gap),
        deeper_gap
      );
      return CURLY_BRACKET_OPEN + join_content(inside, value, gap) + CURLY_BRACKET_CLOSE;
    }, "object_stringify");
    function stringify3(key, holder, gap) {
      let value = holder[key];
      if (isObject(value) && isFunction(value.toJSON)) {
        value = value.toJSON(key);
      }
      if (isFunction(replacer)) {
        value = replacer.call(holder, key, value);
      }
      switch (typeof value) {
        case "string":
          return quote(value);
        case "number":
          return Number.isFinite(value) ? String(value) : STR_NULL;
        case "boolean":
        case "null":
          return String(value);
        // If the type is 'object', we might be dealing with an object or an array or
        // null.
        case "object":
          return isArray(value) ? array_stringify(value, gap) : object_stringify(value, gap);
        // undefined
        default:
      }
    }
    __name(stringify3, "stringify");
    var get_indent = /* @__PURE__ */ __name((space) => isString(space) ? space : isNumber(space) ? repeat(SPACE, space) : EMPTY, "get_indent");
    var { toString } = Object.prototype;
    var PRIMITIVE_OBJECT_TYPES = [
      "[object Number]",
      "[object String]",
      "[object Boolean]"
    ];
    var is_primitive_object = /* @__PURE__ */ __name((subject) => {
      if (typeof subject !== "object") {
        return false;
      }
      const str = toString.call(subject);
      return PRIMITIVE_OBJECT_TYPES.includes(str);
    }, "is_primitive_object");
    module.exports = (value, replacer_, space) => {
      const indent_ = get_indent(space);
      if (!indent_) {
        return JSON.stringify(value, replacer_);
      }
      if (!isFunction(replacer_) && !isArray(replacer_)) {
        replacer_ = null;
      }
      replacer = replacer_;
      indent = indent_;
      const str = is_primitive_object(value) ? JSON.stringify(value) : stringify3("", { "": value }, EMPTY);
      clean();
      return isObject(value) ? process_comments(value, PREFIX_BEFORE_ALL, EMPTY).trimLeft() + str + process_comments(value, PREFIX_AFTER_ALL, EMPTY).trimRight() : str;
    };
  }
});

// node_modules/comment-json/src/index.js
var require_src2 = __commonJS({
  "node_modules/comment-json/src/index.js"(exports, module) {
    init_esbuild_shims();
    var { parse: parse4, tokenize } = require_parse();
    var stringify3 = require_stringify();
    var { CommentArray } = require_array();
    var { assign } = require_common();
    module.exports = {
      parse: parse4,
      stringify: stringify3,
      tokenize,
      CommentArray,
      assign
    };
  }
});

// node_modules/strip-json-comments/index.js
var require_strip_json_comments = __commonJS({
  "node_modules/strip-json-comments/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var singleComment = Symbol("singleComment");
    var multiComment = Symbol("multiComment");
    var stripWithoutWhitespace = /* @__PURE__ */ __name(() => "", "stripWithoutWhitespace");
    var stripWithWhitespace = /* @__PURE__ */ __name((string, start, end) => string.slice(start, end).replace(/\S/g, " "), "stripWithWhitespace");
    var isEscaped = /* @__PURE__ */ __name((jsonString, quotePosition) => {
      let index = quotePosition - 1;
      let backslashCount = 0;
      while (jsonString[index] === "\\") {
        index -= 1;
        backslashCount += 1;
      }
      return Boolean(backslashCount % 2);
    }, "isEscaped");
    module.exports = (jsonString, options = {}) => {
      if (typeof jsonString !== "string") {
        throw new TypeError(`Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``);
      }
      const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
      let insideString = false;
      let insideComment = false;
      let offset = 0;
      let result = "";
      for (let i = 0; i < jsonString.length; i++) {
        const currentCharacter = jsonString[i];
        const nextCharacter = jsonString[i + 1];
        if (!insideComment && currentCharacter === '"') {
          const escaped = isEscaped(jsonString, i);
          if (!escaped) {
            insideString = !insideString;
          }
        }
        if (insideString) {
          continue;
        }
        if (!insideComment && currentCharacter + nextCharacter === "//") {
          result += jsonString.slice(offset, i);
          offset = i;
          insideComment = singleComment;
          i++;
        } else if (insideComment === singleComment && currentCharacter + nextCharacter === "\r\n") {
          i++;
          insideComment = false;
          result += strip(jsonString, offset, i);
          offset = i;
          continue;
        } else if (insideComment === singleComment && currentCharacter === "\n") {
          insideComment = false;
          result += strip(jsonString, offset, i);
          offset = i;
        } else if (!insideComment && currentCharacter + nextCharacter === "/*") {
          result += jsonString.slice(offset, i);
          offset = i;
          insideComment = multiComment;
          i++;
          continue;
        } else if (insideComment === multiComment && currentCharacter + nextCharacter === "*/") {
          i++;
          insideComment = false;
          result += strip(jsonString, offset, i + 1);
          offset = i + 1;
          continue;
        }
      }
      return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
    };
  }
});

// node_modules/picocolors/picocolors.js
var require_picocolors = __commonJS({
  "node_modules/picocolors/picocolors.js"(exports, module) {
    init_esbuild_shims();
    var p = process || {};
    var argv = p.argv || [];
    var env = p.env || {};
    var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
    var formatter = /* @__PURE__ */ __name((open, close, replace = open) => (input) => {
      let string = "" + input, index = string.indexOf(close, open.length);
      return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
    }, "formatter");
    var replaceClose = /* @__PURE__ */ __name((string, close, replace, index) => {
      let result = "", cursor = 0;
      do {
        result += string.substring(cursor, index) + replace;
        cursor = index + close.length;
        index = string.indexOf(close, cursor);
      } while (~index);
      return result + string.substring(cursor);
    }, "replaceClose");
    var createColors = /* @__PURE__ */ __name((enabled = isColorSupported) => {
      let f = enabled ? formatter : () => String;
      return {
        isColorSupported: enabled,
        reset: f("\x1B[0m", "\x1B[0m"),
        bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
        dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
        italic: f("\x1B[3m", "\x1B[23m"),
        underline: f("\x1B[4m", "\x1B[24m"),
        inverse: f("\x1B[7m", "\x1B[27m"),
        hidden: f("\x1B[8m", "\x1B[28m"),
        strikethrough: f("\x1B[9m", "\x1B[29m"),
        black: f("\x1B[30m", "\x1B[39m"),
        red: f("\x1B[31m", "\x1B[39m"),
        green: f("\x1B[32m", "\x1B[39m"),
        yellow: f("\x1B[33m", "\x1B[39m"),
        blue: f("\x1B[34m", "\x1B[39m"),
        magenta: f("\x1B[35m", "\x1B[39m"),
        cyan: f("\x1B[36m", "\x1B[39m"),
        white: f("\x1B[37m", "\x1B[39m"),
        gray: f("\x1B[90m", "\x1B[39m"),
        bgBlack: f("\x1B[40m", "\x1B[49m"),
        bgRed: f("\x1B[41m", "\x1B[49m"),
        bgGreen: f("\x1B[42m", "\x1B[49m"),
        bgYellow: f("\x1B[43m", "\x1B[49m"),
        bgBlue: f("\x1B[44m", "\x1B[49m"),
        bgMagenta: f("\x1B[45m", "\x1B[49m"),
        bgCyan: f("\x1B[46m", "\x1B[49m"),
        bgWhite: f("\x1B[47m", "\x1B[49m"),
        blackBright: f("\x1B[90m", "\x1B[39m"),
        redBright: f("\x1B[91m", "\x1B[39m"),
        greenBright: f("\x1B[92m", "\x1B[39m"),
        yellowBright: f("\x1B[93m", "\x1B[39m"),
        blueBright: f("\x1B[94m", "\x1B[39m"),
        magentaBright: f("\x1B[95m", "\x1B[39m"),
        cyanBright: f("\x1B[96m", "\x1B[39m"),
        whiteBright: f("\x1B[97m", "\x1B[39m"),
        bgBlackBright: f("\x1B[100m", "\x1B[49m"),
        bgRedBright: f("\x1B[101m", "\x1B[49m"),
        bgGreenBright: f("\x1B[102m", "\x1B[49m"),
        bgYellowBright: f("\x1B[103m", "\x1B[49m"),
        bgBlueBright: f("\x1B[104m", "\x1B[49m"),
        bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
        bgCyanBright: f("\x1B[106m", "\x1B[49m"),
        bgWhiteBright: f("\x1B[107m", "\x1B[49m")
      };
    }, "createColors");
    module.exports = createColors();
    module.exports.createColors = createColors;
  }
});

// node_modules/@babel/code-frame/node_modules/js-tokens/index.js
var require_js_tokens = __commonJS({
  "node_modules/@babel/code-frame/node_modules/js-tokens/index.js"(exports) {
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g;
    exports.matchToToken = function(match) {
      var token = { type: "invalid", value: match[0], closed: void 0 };
      if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);
      else if (match[5]) token.type = "comment";
      else if (match[6]) token.type = "comment", token.closed = !!match[7];
      else if (match[8]) token.type = "regex";
      else if (match[9]) token.type = "number";
      else if (match[10]) token.type = "name";
      else if (match[11]) token.type = "punctuator";
      else if (match[12]) token.type = "whitespace";
      return token;
    };
  }
});

// node_modules/@babel/helper-validator-identifier/lib/identifier.js
var require_identifier = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/identifier.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.isIdentifierChar = isIdentifierChar;
    exports.isIdentifierName = isIdentifierName;
    exports.isIdentifierStart = isIdentifierStart;
    var nonASCIIidentifierStartChars = "\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088F\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5C\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDC-\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C8A\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7DC\uA7F1-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC";
    var nonASCIIidentifierChars = "\xB7\u0300-\u036F\u0387\u0483-\u0487\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u0669\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07C0-\u07C9\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u0897-\u089F\u08CA-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0966-\u096F\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09E6-\u09EF\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A66-\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AE6-\u0AEF\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B55-\u0B57\u0B62\u0B63\u0B66-\u0B6F\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0BE6-\u0BEF\u0C00-\u0C04\u0C3C\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0CE6-\u0CEF\u0CF3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D66-\u0D6F\u0D81-\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0E50-\u0E59\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECE\u0ED0-\u0ED9\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1040-\u1049\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F-\u109D\u135D-\u135F\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u17E0-\u17E9\u180B-\u180D\u180F-\u1819\u18A9\u1920-\u192B\u1930-\u193B\u1946-\u194F\u19D0-\u19DA\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AB0-\u1ABD\u1ABF-\u1ADD\u1AE0-\u1AEB\u1B00-\u1B04\u1B34-\u1B44\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BB0-\u1BB9\u1BE6-\u1BF3\u1C24-\u1C37\u1C40-\u1C49\u1C50-\u1C59\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DFF\u200C\u200D\u203F\u2040\u2054\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\u30FB\uA620-\uA629\uA66F\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA82C\uA880\uA881\uA8B4-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F1\uA8FF-\uA909\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9D0-\uA9D9\uA9E5\uA9F0-\uA9F9\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA50-\uAA59\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uABF0-\uABF9\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFF10-\uFF19\uFF3F\uFF65";
    var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
    var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
    nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
    var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 4, 51, 13, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 7, 25, 39, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 39, 27, 10, 22, 251, 41, 7, 1, 17, 5, 57, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 20, 1, 64, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 31, 9, 2, 0, 3, 0, 2, 37, 2, 0, 26, 0, 2, 0, 45, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 200, 32, 32, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 24, 43, 261, 18, 16, 0, 2, 12, 2, 33, 125, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1071, 18, 5, 26, 3994, 6, 582, 6842, 29, 1763, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 433, 44, 212, 63, 33, 24, 3, 24, 45, 74, 6, 0, 67, 12, 65, 1, 2, 0, 15, 4, 10, 7381, 42, 31, 98, 114, 8702, 3, 2, 6, 2, 1, 2, 290, 16, 0, 30, 2, 3, 0, 15, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 7, 5, 262, 61, 147, 44, 11, 6, 17, 0, 322, 29, 19, 43, 485, 27, 229, 29, 3, 0, 208, 30, 2, 2, 2, 1, 2, 6, 3, 4, 10, 1, 225, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4381, 3, 5773, 3, 7472, 16, 621, 2467, 541, 1507, 4938, 6, 8489];
    var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 7, 9, 32, 4, 318, 1, 78, 5, 71, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 3, 0, 158, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 68, 8, 2, 0, 3, 0, 2, 3, 2, 4, 2, 0, 15, 1, 83, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 7, 19, 58, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 199, 7, 137, 9, 54, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 55, 9, 266, 3, 10, 1, 2, 0, 49, 6, 4, 4, 14, 10, 5350, 0, 7, 14, 11465, 27, 2343, 9, 87, 9, 39, 4, 60, 6, 26, 9, 535, 9, 470, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4178, 9, 519, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 101, 0, 161, 6, 10, 9, 357, 0, 62, 13, 499, 13, 245, 1, 2, 9, 233, 0, 3, 0, 8, 1, 6, 0, 475, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
    function isInAstralSet(code, set) {
      let pos = 65536;
      for (let i = 0, length = set.length; i < length; i += 2) {
        pos += set[i];
        if (pos > code) return false;
        pos += set[i + 1];
        if (pos >= code) return true;
      }
      return false;
    }
    __name(isInAstralSet, "isInAstralSet");
    function isIdentifierStart(code) {
      if (code < 65) return code === 36;
      if (code <= 90) return true;
      if (code < 97) return code === 95;
      if (code <= 122) return true;
      if (code <= 65535) {
        return code >= 170 && nonASCIIidentifierStart.test(String.fromCharCode(code));
      }
      return isInAstralSet(code, astralIdentifierStartCodes);
    }
    __name(isIdentifierStart, "isIdentifierStart");
    function isIdentifierChar(code) {
      if (code < 48) return code === 36;
      if (code < 58) return true;
      if (code < 65) return false;
      if (code <= 90) return true;
      if (code < 97) return code === 95;
      if (code <= 122) return true;
      if (code <= 65535) {
        return code >= 170 && nonASCIIidentifier.test(String.fromCharCode(code));
      }
      return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
    }
    __name(isIdentifierChar, "isIdentifierChar");
    function isIdentifierName(name) {
      let isFirst = true;
      for (let i = 0; i < name.length; i++) {
        let cp = name.charCodeAt(i);
        if ((cp & 64512) === 55296 && i + 1 < name.length) {
          const trail = name.charCodeAt(++i);
          if ((trail & 64512) === 56320) {
            cp = 65536 + ((cp & 1023) << 10) + (trail & 1023);
          }
        }
        if (isFirst) {
          isFirst = false;
          if (!isIdentifierStart(cp)) {
            return false;
          }
        } else if (!isIdentifierChar(cp)) {
          return false;
        }
      }
      return !isFirst;
    }
    __name(isIdentifierName, "isIdentifierName");
  }
});

// node_modules/@babel/helper-validator-identifier/lib/keyword.js
var require_keyword = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/keyword.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.isKeyword = isKeyword;
    exports.isReservedWord = isReservedWord;
    exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
    exports.isStrictBindReservedWord = isStrictBindReservedWord;
    exports.isStrictReservedWord = isStrictReservedWord;
    var reservedWords = {
      keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
      strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
      strictBind: ["eval", "arguments"]
    };
    var keywords = new Set(reservedWords.keyword);
    var reservedWordsStrictSet = new Set(reservedWords.strict);
    var reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
    function isReservedWord(word, inModule) {
      return inModule && word === "await" || word === "enum";
    }
    __name(isReservedWord, "isReservedWord");
    function isStrictReservedWord(word, inModule) {
      return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
    }
    __name(isStrictReservedWord, "isStrictReservedWord");
    function isStrictBindOnlyReservedWord(word) {
      return reservedWordsStrictBindSet.has(word);
    }
    __name(isStrictBindOnlyReservedWord, "isStrictBindOnlyReservedWord");
    function isStrictBindReservedWord(word, inModule) {
      return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
    }
    __name(isStrictBindReservedWord, "isStrictBindReservedWord");
    function isKeyword(word) {
      return keywords.has(word);
    }
    __name(isKeyword, "isKeyword");
  }
});

// node_modules/@babel/helper-validator-identifier/lib/index.js
var require_lib = __commonJS({
  "node_modules/@babel/helper-validator-identifier/lib/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    Object.defineProperty(exports, "isIdentifierChar", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierChar;
      }, "get")
    });
    Object.defineProperty(exports, "isIdentifierName", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierName;
      }, "get")
    });
    Object.defineProperty(exports, "isIdentifierStart", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _identifier.isIdentifierStart;
      }, "get")
    });
    Object.defineProperty(exports, "isKeyword", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isKeyword;
      }, "get")
    });
    Object.defineProperty(exports, "isReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isReservedWord;
      }, "get")
    });
    Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictBindOnlyReservedWord;
      }, "get")
    });
    Object.defineProperty(exports, "isStrictBindReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictBindReservedWord;
      }, "get")
    });
    Object.defineProperty(exports, "isStrictReservedWord", {
      enumerable: true,
      get: /* @__PURE__ */ __name(function() {
        return _keyword.isStrictReservedWord;
      }, "get")
    });
    var _identifier = require_identifier();
    var _keyword = require_keyword();
  }
});

// node_modules/@babel/code-frame/lib/index.js
var require_lib2 = __commonJS({
  "node_modules/@babel/code-frame/lib/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    var picocolors = require_picocolors();
    var jsTokens = require_js_tokens();
    var helperValidatorIdentifier = require_lib();
    function isColorSupported() {
      return typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported;
    }
    __name(isColorSupported, "isColorSupported");
    var compose = /* @__PURE__ */ __name((f, g) => (v) => f(g(v)), "compose");
    function buildDefs(colors) {
      return {
        keyword: colors.cyan,
        capitalized: colors.yellow,
        jsxIdentifier: colors.yellow,
        punctuator: colors.yellow,
        number: colors.magenta,
        string: colors.green,
        regex: colors.magenta,
        comment: colors.gray,
        invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
        gutter: colors.gray,
        marker: compose(colors.red, colors.bold),
        message: compose(colors.red, colors.bold),
        reset: colors.reset
      };
    }
    __name(buildDefs, "buildDefs");
    var defsOn = buildDefs(picocolors.createColors(true));
    var defsOff = buildDefs(picocolors.createColors(false));
    function getDefs(enabled) {
      return enabled ? defsOn : defsOff;
    }
    __name(getDefs, "getDefs");
    var sometimesKeywords = /* @__PURE__ */ new Set(["as", "async", "from", "get", "of", "set"]);
    var NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
    var BRACKET = /^[()[\]{}]$/;
    var tokenize;
    var JSX_TAG = /^[a-z][\w-]*$/i;
    var getTokenType = /* @__PURE__ */ __name(function(token, offset, text) {
      if (token.type === "name") {
        const tokenValue = token.value;
        if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
          return "keyword";
        }
        if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
          return "jsxIdentifier";
        }
        const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));
        if (firstChar !== firstChar.toLowerCase()) {
          return "capitalized";
        }
      }
      if (token.type === "punctuator" && BRACKET.test(token.value)) {
        return "bracket";
      }
      if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
        return "punctuator";
      }
      return token.type;
    }, "getTokenType");
    tokenize = /* @__PURE__ */ __name(function* (text) {
      let match;
      while (match = jsTokens.default.exec(text)) {
        const token = jsTokens.matchToToken(match);
        yield {
          type: getTokenType(token, match.index, text),
          value: token.value
        };
      }
    }, "tokenize");
    function highlight(text) {
      if (text === "") return "";
      const defs = getDefs(true);
      let highlighted = "";
      for (const {
        type,
        value
      } of tokenize(text)) {
        if (type in defs) {
          highlighted += value.split(NEWLINE$1).map((str) => defs[type](str)).join("\n");
        } else {
          highlighted += value;
        }
      }
      return highlighted;
    }
    __name(highlight, "highlight");
    var deprecationWarningShown = false;
    var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
    function getMarkerLines(loc, source, opts) {
      const startLoc = Object.assign({
        column: 0,
        line: -1
      }, loc.start);
      const endLoc = Object.assign({}, startLoc, loc.end);
      const {
        linesAbove = 2,
        linesBelow = 3
      } = opts || {};
      const startLine = startLoc.line;
      const startColumn = startLoc.column;
      const endLine = endLoc.line;
      const endColumn = endLoc.column;
      let start = Math.max(startLine - (linesAbove + 1), 0);
      let end = Math.min(source.length, endLine + linesBelow);
      if (startLine === -1) {
        start = 0;
      }
      if (endLine === -1) {
        end = source.length;
      }
      const lineDiff = endLine - startLine;
      const markerLines = {};
      if (lineDiff) {
        for (let i = 0; i <= lineDiff; i++) {
          const lineNumber = i + startLine;
          if (!startColumn) {
            markerLines[lineNumber] = true;
          } else if (i === 0) {
            const sourceLength = source[lineNumber - 1].length;
            markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
          } else if (i === lineDiff) {
            markerLines[lineNumber] = [0, endColumn];
          } else {
            const sourceLength = source[lineNumber - i].length;
            markerLines[lineNumber] = [0, sourceLength];
          }
        }
      } else {
        if (startColumn === endColumn) {
          if (startColumn) {
            markerLines[startLine] = [startColumn, 0];
          } else {
            markerLines[startLine] = true;
          }
        } else {
          markerLines[startLine] = [startColumn, endColumn - startColumn];
        }
      }
      return {
        start,
        end,
        markerLines
      };
    }
    __name(getMarkerLines, "getMarkerLines");
    function codeFrameColumns2(rawLines, loc, opts = {}) {
      const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
      const defs = getDefs(shouldHighlight);
      const lines = rawLines.split(NEWLINE);
      const {
        start,
        end,
        markerLines
      } = getMarkerLines(loc, lines, opts);
      const hasColumns = loc.start && typeof loc.start.column === "number";
      const numberMaxWidth = String(end).length;
      const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
      let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index2) => {
        const number = start + 1 + index2;
        const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
        const gutter = ` ${paddedNumber} |`;
        const hasMarker = markerLines[number];
        const lastMarkerLine = !markerLines[number + 1];
        if (hasMarker) {
          let markerLine = "";
          if (Array.isArray(hasMarker)) {
            const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
            const numberOfMarkers = hasMarker[1] || 1;
            markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
            if (lastMarkerLine && opts.message) {
              markerLine += " " + defs.message(opts.message);
            }
          }
          return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
        } else {
          return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
        }
      }).join("\n");
      if (opts.message && !hasColumns) {
        frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}
${frame}`;
      }
      if (shouldHighlight) {
        return defs.reset(frame);
      } else {
        return frame;
      }
    }
    __name(codeFrameColumns2, "codeFrameColumns");
    function index(rawLines, lineNumber, colNumber, opts = {}) {
      if (!deprecationWarningShown) {
        deprecationWarningShown = true;
        const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
        if (process.emitWarning) {
          process.emitWarning(message, "DeprecationWarning");
        } else {
          const deprecationError = new Error(message);
          deprecationError.name = "DeprecationWarning";
          console.warn(new Error(message));
        }
      }
      colNumber = Math.max(colNumber, 0);
      const location = {
        start: {
          column: colNumber,
          line: lineNumber
        }
      };
      return codeFrameColumns2(rawLines, location, opts);
    }
    __name(index, "index");
    exports.codeFrameColumns = codeFrameColumns2;
    exports.default = index;
    exports.highlight = highlight;
  }
});

// node_modules/semver/internal/debug.js
var require_debug = __commonJS({
  "node_modules/semver/internal/debug.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error("SEMVER", ...args) : () => {
    };
    module.exports = debug;
  }
});

// node_modules/semver/internal/constants.js
var require_constants = __commonJS({
  "node_modules/semver/internal/constants.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var SEMVER_SPEC_VERSION = "2.0.0";
    var MAX_LENGTH = 256;
    var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */
    9007199254740991;
    var MAX_SAFE_COMPONENT_LENGTH = 16;
    var MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6;
    var RELEASE_TYPES = [
      "major",
      "premajor",
      "minor",
      "preminor",
      "patch",
      "prepatch",
      "prerelease"
    ];
    module.exports = {
      MAX_LENGTH,
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_SAFE_INTEGER,
      RELEASE_TYPES,
      SEMVER_SPEC_VERSION,
      FLAG_INCLUDE_PRERELEASE: 1,
      FLAG_LOOSE: 2
    };
  }
});

// node_modules/semver/internal/re.js
var require_re = __commonJS({
  "node_modules/semver/internal/re.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var {
      MAX_SAFE_COMPONENT_LENGTH,
      MAX_SAFE_BUILD_LENGTH,
      MAX_LENGTH
    } = require_constants();
    var debug = require_debug();
    exports = module.exports = {};
    var re = exports.re = [];
    var safeRe = exports.safeRe = [];
    var src = exports.src = [];
    var safeSrc = exports.safeSrc = [];
    var t2 = exports.t = {};
    var R = 0;
    var LETTERDASHNUMBER = "[a-zA-Z0-9-]";
    var safeRegexReplacements = [
      ["\\s", 1],
      ["\\d", MAX_LENGTH],
      [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH]
    ];
    var makeSafeRegex = /* @__PURE__ */ __name((value) => {
      for (const [token, max] of safeRegexReplacements) {
        value = value.split(`${token}*`).join(`${token}{0,${max}}`).split(`${token}+`).join(`${token}{1,${max}}`);
      }
      return value;
    }, "makeSafeRegex");
    var createToken = /* @__PURE__ */ __name((name, value, isGlobal) => {
      const safe = makeSafeRegex(value);
      const index = R++;
      debug(name, index, value);
      t2[name] = index;
      src[index] = value;
      safeSrc[index] = safe;
      re[index] = new RegExp(value, isGlobal ? "g" : void 0);
      safeRe[index] = new RegExp(safe, isGlobal ? "g" : void 0);
    }, "createToken");
    createToken("NUMERICIDENTIFIER", "0|[1-9]\\d*");
    createToken("NUMERICIDENTIFIERLOOSE", "\\d+");
    createToken("NONNUMERICIDENTIFIER", `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`);
    createToken("MAINVERSION", `(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})\\.(${src[t2.NUMERICIDENTIFIER]})`);
    createToken("MAINVERSIONLOOSE", `(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})\\.(${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASEIDENTIFIER", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIER]})`);
    createToken("PRERELEASEIDENTIFIERLOOSE", `(?:${src[t2.NONNUMERICIDENTIFIER]}|${src[t2.NUMERICIDENTIFIERLOOSE]})`);
    createToken("PRERELEASE", `(?:-(${src[t2.PRERELEASEIDENTIFIER]}(?:\\.${src[t2.PRERELEASEIDENTIFIER]})*))`);
    createToken("PRERELEASELOOSE", `(?:-?(${src[t2.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t2.PRERELEASEIDENTIFIERLOOSE]})*))`);
    createToken("BUILDIDENTIFIER", `${LETTERDASHNUMBER}+`);
    createToken("BUILD", `(?:\\+(${src[t2.BUILDIDENTIFIER]}(?:\\.${src[t2.BUILDIDENTIFIER]})*))`);
    createToken("FULLPLAIN", `v?${src[t2.MAINVERSION]}${src[t2.PRERELEASE]}?${src[t2.BUILD]}?`);
    createToken("FULL", `^${src[t2.FULLPLAIN]}$`);
    createToken("LOOSEPLAIN", `[v=\\s]*${src[t2.MAINVERSIONLOOSE]}${src[t2.PRERELEASELOOSE]}?${src[t2.BUILD]}?`);
    createToken("LOOSE", `^${src[t2.LOOSEPLAIN]}$`);
    createToken("GTLT", "((?:<|>)?=?)");
    createToken("XRANGEIDENTIFIERLOOSE", `${src[t2.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
    createToken("XRANGEIDENTIFIER", `${src[t2.NUMERICIDENTIFIER]}|x|X|\\*`);
    createToken("XRANGEPLAIN", `[v=\\s]*(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:\\.(${src[t2.XRANGEIDENTIFIER]})(?:${src[t2.PRERELEASE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGEPLAINLOOSE", `[v=\\s]*(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:\\.(${src[t2.XRANGEIDENTIFIERLOOSE]})(?:${src[t2.PRERELEASELOOSE]})?${src[t2.BUILD]}?)?)?`);
    createToken("XRANGE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAIN]}$`);
    createToken("XRANGELOOSE", `^${src[t2.GTLT]}\\s*${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COERCEPLAIN", `${"(^|[^\\d])(\\d{1,"}${MAX_SAFE_COMPONENT_LENGTH}})(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`);
    createToken("COERCE", `${src[t2.COERCEPLAIN]}(?:$|[^\\d])`);
    createToken("COERCEFULL", src[t2.COERCEPLAIN] + `(?:${src[t2.PRERELEASE]})?(?:${src[t2.BUILD]})?(?:$|[^\\d])`);
    createToken("COERCERTL", src[t2.COERCE], true);
    createToken("COERCERTLFULL", src[t2.COERCEFULL], true);
    createToken("LONETILDE", "(?:~>?)");
    createToken("TILDETRIM", `(\\s*)${src[t2.LONETILDE]}\\s+`, true);
    exports.tildeTrimReplace = "$1~";
    createToken("TILDE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAIN]}$`);
    createToken("TILDELOOSE", `^${src[t2.LONETILDE]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("LONECARET", "(?:\\^)");
    createToken("CARETTRIM", `(\\s*)${src[t2.LONECARET]}\\s+`, true);
    exports.caretTrimReplace = "$1^";
    createToken("CARET", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAIN]}$`);
    createToken("CARETLOOSE", `^${src[t2.LONECARET]}${src[t2.XRANGEPLAINLOOSE]}$`);
    createToken("COMPARATORLOOSE", `^${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]})$|^$`);
    createToken("COMPARATOR", `^${src[t2.GTLT]}\\s*(${src[t2.FULLPLAIN]})$|^$`);
    createToken("COMPARATORTRIM", `(\\s*)${src[t2.GTLT]}\\s*(${src[t2.LOOSEPLAIN]}|${src[t2.XRANGEPLAIN]})`, true);
    exports.comparatorTrimReplace = "$1$2$3";
    createToken("HYPHENRANGE", `^\\s*(${src[t2.XRANGEPLAIN]})\\s+-\\s+(${src[t2.XRANGEPLAIN]})\\s*$`);
    createToken("HYPHENRANGELOOSE", `^\\s*(${src[t2.XRANGEPLAINLOOSE]})\\s+-\\s+(${src[t2.XRANGEPLAINLOOSE]})\\s*$`);
    createToken("STAR", "(<|>)?=?\\s*\\*");
    createToken("GTE0", "^\\s*>=\\s*0\\.0\\.0\\s*$");
    createToken("GTE0PRE", "^\\s*>=\\s*0\\.0\\.0-0\\s*$");
  }
});

// node_modules/semver/internal/parse-options.js
var require_parse_options = __commonJS({
  "node_modules/semver/internal/parse-options.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var looseOption = Object.freeze({ loose: true });
    var emptyOpts = Object.freeze({});
    var parseOptions = /* @__PURE__ */ __name((options) => {
      if (!options) {
        return emptyOpts;
      }
      if (typeof options !== "object") {
        return looseOption;
      }
      return options;
    }, "parseOptions");
    module.exports = parseOptions;
  }
});

// node_modules/semver/internal/identifiers.js
var require_identifiers = __commonJS({
  "node_modules/semver/internal/identifiers.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var numeric = /^[0-9]+$/;
    var compareIdentifiers = /* @__PURE__ */ __name((a, b) => {
      if (typeof a === "number" && typeof b === "number") {
        return a === b ? 0 : a < b ? -1 : 1;
      }
      const anum = numeric.test(a);
      const bnum = numeric.test(b);
      if (anum && bnum) {
        a = +a;
        b = +b;
      }
      return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
    }, "compareIdentifiers");
    var rcompareIdentifiers = /* @__PURE__ */ __name((a, b) => compareIdentifiers(b, a), "rcompareIdentifiers");
    module.exports = {
      compareIdentifiers,
      rcompareIdentifiers
    };
  }
});

// node_modules/semver/classes/semver.js
var require_semver = __commonJS({
  "node_modules/semver/classes/semver.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var debug = require_debug();
    var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants();
    var { safeRe: re, t: t2 } = require_re();
    var parseOptions = require_parse_options();
    var { compareIdentifiers } = require_identifiers();
    var SemVer = class _SemVer {
      static {
        __name(this, "SemVer");
      }
      constructor(version, options) {
        options = parseOptions(options);
        if (version instanceof _SemVer) {
          if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
            return version;
          } else {
            version = version.version;
          }
        } else if (typeof version !== "string") {
          throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`);
        }
        if (version.length > MAX_LENGTH) {
          throw new TypeError(
            `version is longer than ${MAX_LENGTH} characters`
          );
        }
        debug("SemVer", version, options);
        this.options = options;
        this.loose = !!options.loose;
        this.includePrerelease = !!options.includePrerelease;
        const m = version.trim().match(options.loose ? re[t2.LOOSE] : re[t2.FULL]);
        if (!m) {
          throw new TypeError(`Invalid Version: ${version}`);
        }
        this.raw = version;
        this.major = +m[1];
        this.minor = +m[2];
        this.patch = +m[3];
        if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
          throw new TypeError("Invalid major version");
        }
        if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
          throw new TypeError("Invalid minor version");
        }
        if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
          throw new TypeError("Invalid patch version");
        }
        if (!m[4]) {
          this.prerelease = [];
        } else {
          this.prerelease = m[4].split(".").map((id) => {
            if (/^[0-9]+$/.test(id)) {
              const num = +id;
              if (num >= 0 && num < MAX_SAFE_INTEGER) {
                return num;
              }
            }
            return id;
          });
        }
        this.build = m[5] ? m[5].split(".") : [];
        this.format();
      }
      format() {
        this.version = `${this.major}.${this.minor}.${this.patch}`;
        if (this.prerelease.length) {
          this.version += `-${this.prerelease.join(".")}`;
        }
        return this.version;
      }
      toString() {
        return this.version;
      }
      compare(other) {
        debug("SemVer.compare", this.version, this.options, other);
        if (!(other instanceof _SemVer)) {
          if (typeof other === "string" && other === this.version) {
            return 0;
          }
          other = new _SemVer(other, this.options);
        }
        if (other.version === this.version) {
          return 0;
        }
        return this.compareMain(other) || this.comparePre(other);
      }
      compareMain(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.major < other.major) {
          return -1;
        }
        if (this.major > other.major) {
          return 1;
        }
        if (this.minor < other.minor) {
          return -1;
        }
        if (this.minor > other.minor) {
          return 1;
        }
        if (this.patch < other.patch) {
          return -1;
        }
        if (this.patch > other.patch) {
          return 1;
        }
        return 0;
      }
      comparePre(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        if (this.prerelease.length && !other.prerelease.length) {
          return -1;
        } else if (!this.prerelease.length && other.prerelease.length) {
          return 1;
        } else if (!this.prerelease.length && !other.prerelease.length) {
          return 0;
        }
        let i = 0;
        do {
          const a = this.prerelease[i];
          const b = other.prerelease[i];
          debug("prerelease compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      compareBuild(other) {
        if (!(other instanceof _SemVer)) {
          other = new _SemVer(other, this.options);
        }
        let i = 0;
        do {
          const a = this.build[i];
          const b = other.build[i];
          debug("build compare", i, a, b);
          if (a === void 0 && b === void 0) {
            return 0;
          } else if (b === void 0) {
            return 1;
          } else if (a === void 0) {
            return -1;
          } else if (a === b) {
            continue;
          } else {
            return compareIdentifiers(a, b);
          }
        } while (++i);
      }
      // preminor will bump the version up to the next minor release, and immediately
      // down to pre-release. premajor and prepatch work the same way.
      inc(release, identifier, identifierBase) {
        if (release.startsWith("pre")) {
          if (!identifier && identifierBase === false) {
            throw new Error("invalid increment argument: identifier is empty");
          }
          if (identifier) {
            const match = `-${identifier}`.match(this.options.loose ? re[t2.PRERELEASELOOSE] : re[t2.PRERELEASE]);
            if (!match || match[1] !== identifier) {
              throw new Error(`invalid identifier: ${identifier}`);
            }
          }
        }
        switch (release) {
          case "premajor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor = 0;
            this.major++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "preminor":
            this.prerelease.length = 0;
            this.patch = 0;
            this.minor++;
            this.inc("pre", identifier, identifierBase);
            break;
          case "prepatch":
            this.prerelease.length = 0;
            this.inc("patch", identifier, identifierBase);
            this.inc("pre", identifier, identifierBase);
            break;
          // If the input is a non-prerelease version, this acts the same as
          // prepatch.
          case "prerelease":
            if (this.prerelease.length === 0) {
              this.inc("patch", identifier, identifierBase);
            }
            this.inc("pre", identifier, identifierBase);
            break;
          case "release":
            if (this.prerelease.length === 0) {
              throw new Error(`version ${this.raw} is not a prerelease`);
            }
            this.prerelease.length = 0;
            break;
          case "major":
            if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
              this.major++;
            }
            this.minor = 0;
            this.patch = 0;
            this.prerelease = [];
            break;
          case "minor":
            if (this.patch !== 0 || this.prerelease.length === 0) {
              this.minor++;
            }
            this.patch = 0;
            this.prerelease = [];
            break;
          case "patch":
            if (this.prerelease.length === 0) {
              this.patch++;
            }
            this.prerelease = [];
            break;
          // This probably shouldn't be used publicly.
          // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
          case "pre": {
            const base = Number(identifierBase) ? 1 : 0;
            if (this.prerelease.length === 0) {
              this.prerelease = [base];
            } else {
              let i = this.prerelease.length;
              while (--i >= 0) {
                if (typeof this.prerelease[i] === "number") {
                  this.prerelease[i]++;
                  i = -2;
                }
              }
              if (i === -1) {
                if (identifier === this.prerelease.join(".") && identifierBase === false) {
                  throw new Error("invalid increment argument: identifier already exists");
                }
                this.prerelease.push(base);
              }
            }
            if (identifier) {
              let prerelease = [identifier, base];
              if (identifierBase === false) {
                prerelease = [identifier];
              }
              if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
                if (isNaN(this.prerelease[1])) {
                  this.prerelease = prerelease;
                }
              } else {
                this.prerelease = prerelease;
              }
            }
            break;
          }
          default:
            throw new Error(`invalid increment argument: ${release}`);
        }
        this.raw = this.format();
        if (this.build.length) {
          this.raw += `+${this.build.join(".")}`;
        }
        return this;
      }
    };
    module.exports = SemVer;
  }
});

// node_modules/semver/functions/parse.js
var require_parse2 = __commonJS({
  "node_modules/semver/functions/parse.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var SemVer = require_semver();
    var parse4 = /* @__PURE__ */ __name((version, options, throwErrors = false) => {
      if (version instanceof SemVer) {
        return version;
      }
      try {
        return new SemVer(version, options);
      } catch (er) {
        if (!throwErrors) {
          return null;
        }
        throw er;
      }
    }, "parse");
    module.exports = parse4;
  }
});

// node_modules/semver/functions/valid.js
var require_valid = __commonJS({
  "node_modules/semver/functions/valid.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var parse4 = require_parse2();
    var valid = /* @__PURE__ */ __name((version, options) => {
      const v = parse4(version, options);
      return v ? v.version : null;
    }, "valid");
    module.exports = valid;
  }
});

// node_modules/semver/functions/clean.js
var require_clean = __commonJS({
  "node_modules/semver/functions/clean.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var parse4 = require_parse2();
    var clean = /* @__PURE__ */ __name((version, options) => {
      const s = parse4(version.trim().replace(/^[=v]+/, ""), options);
      return s ? s.version : null;
    }, "clean");
    module.exports = clean;
  }
});

// node_modules/spdx-license-ids/index.json
var require_spdx_license_ids = __commonJS({
  "node_modules/spdx-license-ids/index.json"(exports, module) {
    module.exports = [
      "0BSD",
      "3D-Slicer-1.0",
      "AAL",
      "ADSL",
      "AFL-1.1",
      "AFL-1.2",
      "AFL-2.0",
      "AFL-2.1",
      "AFL-3.0",
      "AGPL-1.0-only",
      "AGPL-1.0-or-later",
      "AGPL-3.0-only",
      "AGPL-3.0-or-later",
      "AMD-newlib",
      "AMDPLPA",
      "AML",
      "AML-glslang",
      "AMPAS",
      "ANTLR-PD",
      "ANTLR-PD-fallback",
      "APAFML",
      "APL-1.0",
      "APSL-1.0",
      "APSL-1.1",
      "APSL-1.2",
      "APSL-2.0",
      "ASWF-Digital-Assets-1.0",
      "ASWF-Digital-Assets-1.1",
      "Abstyles",
      "AdaCore-doc",
      "Adobe-2006",
      "Adobe-Display-PostScript",
      "Adobe-Glyph",
      "Adobe-Utopia",
      "Afmparse",
      "Aladdin",
      "Apache-1.0",
      "Apache-1.1",
      "Apache-2.0",
      "App-s2p",
      "Arphic-1999",
      "Artistic-1.0",
      "Artistic-1.0-Perl",
      "Artistic-1.0-cl8",
      "Artistic-2.0",
      "BSD-1-Clause",
      "BSD-2-Clause",
      "BSD-2-Clause-Darwin",
      "BSD-2-Clause-Patent",
      "BSD-2-Clause-Views",
      "BSD-2-Clause-first-lines",
      "BSD-3-Clause",
      "BSD-3-Clause-Attribution",
      "BSD-3-Clause-Clear",
      "BSD-3-Clause-HP",
      "BSD-3-Clause-LBNL",
      "BSD-3-Clause-Modification",
      "BSD-3-Clause-No-Military-License",
      "BSD-3-Clause-No-Nuclear-License",
      "BSD-3-Clause-No-Nuclear-License-2014",
      "BSD-3-Clause-No-Nuclear-Warranty",
      "BSD-3-Clause-Open-MPI",
      "BSD-3-Clause-Sun",
      "BSD-3-Clause-acpica",
      "BSD-3-Clause-flex",
      "BSD-4-Clause",
      "BSD-4-Clause-Shortened",
      "BSD-4-Clause-UC",
      "BSD-4.3RENO",
      "BSD-4.3TAHOE",
      "BSD-Advertising-Acknowledgement",
      "BSD-Attribution-HPND-disclaimer",
      "BSD-Inferno-Nettverk",
      "BSD-Protection",
      "BSD-Source-Code",
      "BSD-Source-beginning-file",
      "BSD-Systemics",
      "BSD-Systemics-W3Works",
      "BSL-1.0",
      "BUSL-1.1",
      "Baekmuk",
      "Bahyph",
      "Barr",
      "Beerware",
      "BitTorrent-1.0",
      "BitTorrent-1.1",
      "Bitstream-Charter",
      "Bitstream-Vera",
      "BlueOak-1.0.0",
      "Boehm-GC",
      "Boehm-GC-without-fee",
      "Borceux",
      "Brian-Gladman-2-Clause",
      "Brian-Gladman-3-Clause",
      "C-UDA-1.0",
      "CAL-1.0",
      "CAL-1.0-Combined-Work-Exception",
      "CATOSL-1.1",
      "CC-BY-1.0",
      "CC-BY-2.0",
      "CC-BY-2.5",
      "CC-BY-2.5-AU",
      "CC-BY-3.0",
      "CC-BY-3.0-AT",
      "CC-BY-3.0-AU",
      "CC-BY-3.0-DE",
      "CC-BY-3.0-IGO",
      "CC-BY-3.0-NL",
      "CC-BY-3.0-US",
      "CC-BY-4.0",
      "CC-BY-NC-1.0",
      "CC-BY-NC-2.0",
      "CC-BY-NC-2.5",
      "CC-BY-NC-3.0",
      "CC-BY-NC-3.0-DE",
      "CC-BY-NC-4.0",
      "CC-BY-NC-ND-1.0",
      "CC-BY-NC-ND-2.0",
      "CC-BY-NC-ND-2.5",
      "CC-BY-NC-ND-3.0",
      "CC-BY-NC-ND-3.0-DE",
      "CC-BY-NC-ND-3.0-IGO",
      "CC-BY-NC-ND-4.0",
      "CC-BY-NC-SA-1.0",
      "CC-BY-NC-SA-2.0",
      "CC-BY-NC-SA-2.0-DE",
      "CC-BY-NC-SA-2.0-FR",
      "CC-BY-NC-SA-2.0-UK",
      "CC-BY-NC-SA-2.5",
      "CC-BY-NC-SA-3.0",
      "CC-BY-NC-SA-3.0-DE",
      "CC-BY-NC-SA-3.0-IGO",
      "CC-BY-NC-SA-4.0",
      "CC-BY-ND-1.0",
      "CC-BY-ND-2.0",
      "CC-BY-ND-2.5",
      "CC-BY-ND-3.0",
      "CC-BY-ND-3.0-DE",
      "CC-BY-ND-4.0",
      "CC-BY-SA-1.0",
      "CC-BY-SA-2.0",
      "CC-BY-SA-2.0-UK",
      "CC-BY-SA-2.1-JP",
      "CC-BY-SA-2.5",
      "CC-BY-SA-3.0",
      "CC-BY-SA-3.0-AT",
      "CC-BY-SA-3.0-DE",
      "CC-BY-SA-3.0-IGO",
      "CC-BY-SA-4.0",
      "CC-PDDC",
      "CC-PDM-1.0",
      "CC-SA-1.0",
      "CC0-1.0",
      "CDDL-1.0",
      "CDDL-1.1",
      "CDL-1.0",
      "CDLA-Permissive-1.0",
      "CDLA-Permissive-2.0",
      "CDLA-Sharing-1.0",
      "CECILL-1.0",
      "CECILL-1.1",
      "CECILL-2.0",
      "CECILL-2.1",
      "CECILL-B",
      "CECILL-C",
      "CERN-OHL-1.1",
      "CERN-OHL-1.2",
      "CERN-OHL-P-2.0",
      "CERN-OHL-S-2.0",
      "CERN-OHL-W-2.0",
      "CFITSIO",
      "CMU-Mach",
      "CMU-Mach-nodoc",
      "CNRI-Jython",
      "CNRI-Python",
      "CNRI-Python-GPL-Compatible",
      "COIL-1.0",
      "CPAL-1.0",
      "CPL-1.0",
      "CPOL-1.02",
      "CUA-OPL-1.0",
      "Caldera",
      "Caldera-no-preamble",
      "Catharon",
      "ClArtistic",
      "Clips",
      "Community-Spec-1.0",
      "Condor-1.1",
      "Cornell-Lossless-JPEG",
      "Cronyx",
      "Crossword",
      "CrystalStacker",
      "Cube",
      "D-FSL-1.0",
      "DEC-3-Clause",
      "DL-DE-BY-2.0",
      "DL-DE-ZERO-2.0",
      "DOC",
      "DRL-1.0",
      "DRL-1.1",
      "DSDP",
      "DocBook-Schema",
      "DocBook-Stylesheet",
      "DocBook-XML",
      "Dotseqn",
      "ECL-1.0",
      "ECL-2.0",
      "EFL-1.0",
      "EFL-2.0",
      "EPICS",
      "EPL-1.0",
      "EPL-2.0",
      "EUDatagrid",
      "EUPL-1.0",
      "EUPL-1.1",
      "EUPL-1.2",
      "Elastic-2.0",
      "Entessa",
      "ErlPL-1.1",
      "Eurosym",
      "FBM",
      "FDK-AAC",
      "FSFAP",
      "FSFAP-no-warranty-disclaimer",
      "FSFUL",
      "FSFULLR",
      "FSFULLRWD",
      "FTL",
      "Fair",
      "Ferguson-Twofish",
      "Frameworx-1.0",
      "FreeBSD-DOC",
      "FreeImage",
      "Furuseth",
      "GCR-docs",
      "GD",
      "GFDL-1.1-invariants-only",
      "GFDL-1.1-invariants-or-later",
      "GFDL-1.1-no-invariants-only",
      "GFDL-1.1-no-invariants-or-later",
      "GFDL-1.1-only",
      "GFDL-1.1-or-later",
      "GFDL-1.2-invariants-only",
      "GFDL-1.2-invariants-or-later",
      "GFDL-1.2-no-invariants-only",
      "GFDL-1.2-no-invariants-or-later",
      "GFDL-1.2-only",
      "GFDL-1.2-or-later",
      "GFDL-1.3-invariants-only",
      "GFDL-1.3-invariants-or-later",
      "GFDL-1.3-no-invariants-only",
      "GFDL-1.3-no-invariants-or-later",
      "GFDL-1.3-only",
      "GFDL-1.3-or-later",
      "GL2PS",
      "GLWTPL",
      "GPL-1.0-only",
      "GPL-1.0-or-later",
      "GPL-2.0-only",
      "GPL-2.0-or-later",
      "GPL-3.0-only",
      "GPL-3.0-or-later",
      "Giftware",
      "Glide",
      "Glulxe",
      "Graphics-Gems",
      "Gutmann",
      "HIDAPI",
      "HP-1986",
      "HP-1989",
      "HPND",
      "HPND-DEC",
      "HPND-Fenneberg-Livingston",
      "HPND-INRIA-IMAG",
      "HPND-Intel",
      "HPND-Kevlin-Henney",
      "HPND-MIT-disclaimer",
      "HPND-Markus-Kuhn",
      "HPND-Netrek",
      "HPND-Pbmplus",
      "HPND-UC",
      "HPND-UC-export-US",
      "HPND-doc",
      "HPND-doc-sell",
      "HPND-export-US",
      "HPND-export-US-acknowledgement",
      "HPND-export-US-modify",
      "HPND-export2-US",
      "HPND-merchantability-variant",
      "HPND-sell-MIT-disclaimer-xserver",
      "HPND-sell-regexpr",
      "HPND-sell-variant",
      "HPND-sell-variant-MIT-disclaimer",
      "HPND-sell-variant-MIT-disclaimer-rev",
      "HTMLTIDY",
      "HaskellReport",
      "Hippocratic-2.1",
      "IBM-pibs",
      "ICU",
      "IEC-Code-Components-EULA",
      "IJG",
      "IJG-short",
      "IPA",
      "IPL-1.0",
      "ISC",
      "ISC-Veillard",
      "ImageMagick",
      "Imlib2",
      "Info-ZIP",
      "Inner-Net-2.0",
      "InnoSetup",
      "Intel",
      "Intel-ACPI",
      "Interbase-1.0",
      "JPL-image",
      "JPNIC",
      "JSON",
      "Jam",
      "JasPer-2.0",
      "Kastrup",
      "Kazlib",
      "Knuth-CTAN",
      "LAL-1.2",
      "LAL-1.3",
      "LGPL-2.0-only",
      "LGPL-2.0-or-later",
      "LGPL-2.1-only",
      "LGPL-2.1-or-later",
      "LGPL-3.0-only",
      "LGPL-3.0-or-later",
      "LGPLLR",
      "LOOP",
      "LPD-document",
      "LPL-1.0",
      "LPL-1.02",
      "LPPL-1.0",
      "LPPL-1.1",
      "LPPL-1.2",
      "LPPL-1.3a",
      "LPPL-1.3c",
      "LZMA-SDK-9.11-to-9.20",
      "LZMA-SDK-9.22",
      "Latex2e",
      "Latex2e-translated-notice",
      "Leptonica",
      "LiLiQ-P-1.1",
      "LiLiQ-R-1.1",
      "LiLiQ-Rplus-1.1",
      "Libpng",
      "Linux-OpenIB",
      "Linux-man-pages-1-para",
      "Linux-man-pages-copyleft",
      "Linux-man-pages-copyleft-2-para",
      "Linux-man-pages-copyleft-var",
      "Lucida-Bitmap-Fonts",
      "MIPS",
      "MIT",
      "MIT-0",
      "MIT-CMU",
      "MIT-Click",
      "MIT-Festival",
      "MIT-Khronos-old",
      "MIT-Modern-Variant",
      "MIT-Wu",
      "MIT-advertising",
      "MIT-enna",
      "MIT-feh",
      "MIT-open-group",
      "MIT-testregex",
      "MITNFA",
      "MMIXware",
      "MPEG-SSG",
      "MPL-1.0",
      "MPL-1.1",
      "MPL-2.0",
      "MPL-2.0-no-copyleft-exception",
      "MS-LPL",
      "MS-PL",
      "MS-RL",
      "MTLL",
      "Mackerras-3-Clause",
      "Mackerras-3-Clause-acknowledgment",
      "MakeIndex",
      "Martin-Birgmeier",
      "McPhee-slideshow",
      "Minpack",
      "MirOS",
      "Motosoto",
      "MulanPSL-1.0",
      "MulanPSL-2.0",
      "Multics",
      "Mup",
      "NAIST-2003",
      "NASA-1.3",
      "NBPL-1.0",
      "NCBI-PD",
      "NCGL-UK-2.0",
      "NCL",
      "NCSA",
      "NGPL",
      "NICTA-1.0",
      "NIST-PD",
      "NIST-PD-fallback",
      "NIST-Software",
      "NLOD-1.0",
      "NLOD-2.0",
      "NLPL",
      "NOSL",
      "NPL-1.0",
      "NPL-1.1",
      "NPOSL-3.0",
      "NRL",
      "NTP",
      "NTP-0",
      "Naumen",
      "NetCDF",
      "Newsletr",
      "Nokia",
      "Noweb",
      "O-UDA-1.0",
      "OAR",
      "OCCT-PL",
      "OCLC-2.0",
      "ODC-By-1.0",
      "ODbL-1.0",
      "OFFIS",
      "OFL-1.0",
      "OFL-1.0-RFN",
      "OFL-1.0-no-RFN",
      "OFL-1.1",
      "OFL-1.1-RFN",
      "OFL-1.1-no-RFN",
      "OGC-1.0",
      "OGDL-Taiwan-1.0",
      "OGL-Canada-2.0",
      "OGL-UK-1.0",
      "OGL-UK-2.0",
      "OGL-UK-3.0",
      "OGTSL",
      "OLDAP-1.1",
      "OLDAP-1.2",
      "OLDAP-1.3",
      "OLDAP-1.4",
      "OLDAP-2.0",
      "OLDAP-2.0.1",
      "OLDAP-2.1",
      "OLDAP-2.2",
      "OLDAP-2.2.1",
      "OLDAP-2.2.2",
      "OLDAP-2.3",
      "OLDAP-2.4",
      "OLDAP-2.5",
      "OLDAP-2.6",
      "OLDAP-2.7",
      "OLDAP-2.8",
      "OLFL-1.3",
      "OML",
      "OPL-1.0",
      "OPL-UK-3.0",
      "OPUBL-1.0",
      "OSET-PL-2.1",
      "OSL-1.0",
      "OSL-1.1",
      "OSL-2.0",
      "OSL-2.1",
      "OSL-3.0",
      "OpenPBS-2.3",
      "OpenSSL",
      "OpenSSL-standalone",
      "OpenVision",
      "PADL",
      "PDDL-1.0",
      "PHP-3.0",
      "PHP-3.01",
      "PPL",
      "PSF-2.0",
      "Parity-6.0.0",
      "Parity-7.0.0",
      "Pixar",
      "Plexus",
      "PolyForm-Noncommercial-1.0.0",
      "PolyForm-Small-Business-1.0.0",
      "PostgreSQL",
      "Python-2.0",
      "Python-2.0.1",
      "QPL-1.0",
      "QPL-1.0-INRIA-2004",
      "Qhull",
      "RHeCos-1.1",
      "RPL-1.1",
      "RPL-1.5",
      "RPSL-1.0",
      "RSA-MD",
      "RSCPL",
      "Rdisc",
      "Ruby",
      "Ruby-pty",
      "SAX-PD",
      "SAX-PD-2.0",
      "SCEA",
      "SGI-B-1.0",
      "SGI-B-1.1",
      "SGI-B-2.0",
      "SGI-OpenGL",
      "SGP4",
      "SHL-0.5",
      "SHL-0.51",
      "SISSL",
      "SISSL-1.2",
      "SL",
      "SMAIL-GPL",
      "SMLNJ",
      "SMPPL",
      "SNIA",
      "SPL-1.0",
      "SSH-OpenSSH",
      "SSH-short",
      "SSLeay-standalone",
      "SSPL-1.0",
      "SWL",
      "Saxpath",
      "SchemeReport",
      "Sendmail",
      "Sendmail-8.23",
      "Sendmail-Open-Source-1.1",
      "SimPL-2.0",
      "Sleepycat",
      "Soundex",
      "Spencer-86",
      "Spencer-94",
      "Spencer-99",
      "SugarCRM-1.1.3",
      "Sun-PPP",
      "Sun-PPP-2000",
      "SunPro",
      "Symlinks",
      "TAPR-OHL-1.0",
      "TCL",
      "TCP-wrappers",
      "TGPPL-1.0",
      "TMate",
      "TORQUE-1.1",
      "TOSL",
      "TPDL",
      "TPL-1.0",
      "TTWL",
      "TTYP0",
      "TU-Berlin-1.0",
      "TU-Berlin-2.0",
      "TermReadKey",
      "ThirdEye",
      "TrustedQSL",
      "UCAR",
      "UCL-1.0",
      "UMich-Merit",
      "UPL-1.0",
      "URT-RLE",
      "Ubuntu-font-1.0",
      "Unicode-3.0",
      "Unicode-DFS-2015",
      "Unicode-DFS-2016",
      "Unicode-TOU",
      "UnixCrypt",
      "Unlicense",
      "VOSTROM",
      "VSL-1.0",
      "Vim",
      "W3C",
      "W3C-19980720",
      "W3C-20150513",
      "WTFPL",
      "Watcom-1.0",
      "Widget-Workshop",
      "Wsuipa",
      "X11",
      "X11-distribute-modifications-variant",
      "X11-swapped",
      "XFree86-1.1",
      "XSkat",
      "Xdebug-1.03",
      "Xerox",
      "Xfig",
      "Xnet",
      "YPL-1.0",
      "YPL-1.1",
      "ZPL-1.1",
      "ZPL-2.0",
      "ZPL-2.1",
      "Zed",
      "Zeeff",
      "Zend-2.0",
      "Zimbra-1.3",
      "Zimbra-1.4",
      "Zlib",
      "any-OSI",
      "any-OSI-perl-modules",
      "bcrypt-Solar-Designer",
      "blessing",
      "bzip2-1.0.6",
      "check-cvs",
      "checkmk",
      "copyleft-next-0.3.0",
      "copyleft-next-0.3.1",
      "curl",
      "cve-tou",
      "diffmark",
      "dtoa",
      "dvipdfm",
      "eGenix",
      "etalab-2.0",
      "fwlw",
      "gSOAP-1.3b",
      "generic-xts",
      "gnuplot",
      "gtkbook",
      "hdparm",
      "iMatix",
      "libpng-2.0",
      "libselinux-1.0",
      "libtiff",
      "libutil-David-Nugent",
      "lsof",
      "magaz",
      "mailprio",
      "metamail",
      "mpi-permissive",
      "mpich2",
      "mplus",
      "pkgconf",
      "pnmstitch",
      "psfrag",
      "psutils",
      "python-ldap",
      "radvd",
      "snprintf",
      "softSurfer",
      "ssh-keyscan",
      "swrule",
      "threeparttable",
      "ulem",
      "w3m",
      "wwl",
      "xinetd",
      "xkeyboard-config-Zinoviev",
      "xlock",
      "xpp",
      "xzoom",
      "zlib-acknowledgement"
    ];
  }
});

// node_modules/spdx-license-ids/deprecated.json
var require_deprecated = __commonJS({
  "node_modules/spdx-license-ids/deprecated.json"(exports, module) {
    module.exports = [
      "AGPL-1.0",
      "AGPL-3.0",
      "BSD-2-Clause-FreeBSD",
      "BSD-2-Clause-NetBSD",
      "GFDL-1.1",
      "GFDL-1.2",
      "GFDL-1.3",
      "GPL-1.0",
      "GPL-2.0",
      "GPL-2.0-with-GCC-exception",
      "GPL-2.0-with-autoconf-exception",
      "GPL-2.0-with-bison-exception",
      "GPL-2.0-with-classpath-exception",
      "GPL-2.0-with-font-exception",
      "GPL-3.0",
      "GPL-3.0-with-GCC-exception",
      "GPL-3.0-with-autoconf-exception",
      "LGPL-2.0",
      "LGPL-2.1",
      "LGPL-3.0",
      "Net-SNMP",
      "Nunit",
      "StandardML-NJ",
      "bzip2-1.0.5",
      "eCos-2.0",
      "wxWindows"
    ];
  }
});

// node_modules/spdx-exceptions/index.json
var require_spdx_exceptions = __commonJS({
  "node_modules/spdx-exceptions/index.json"(exports, module) {
    module.exports = [
      "389-exception",
      "Asterisk-exception",
      "Autoconf-exception-2.0",
      "Autoconf-exception-3.0",
      "Autoconf-exception-generic",
      "Autoconf-exception-generic-3.0",
      "Autoconf-exception-macro",
      "Bison-exception-1.24",
      "Bison-exception-2.2",
      "Bootloader-exception",
      "Classpath-exception-2.0",
      "CLISP-exception-2.0",
      "cryptsetup-OpenSSL-exception",
      "DigiRule-FOSS-exception",
      "eCos-exception-2.0",
      "Fawkes-Runtime-exception",
      "FLTK-exception",
      "fmt-exception",
      "Font-exception-2.0",
      "freertos-exception-2.0",
      "GCC-exception-2.0",
      "GCC-exception-2.0-note",
      "GCC-exception-3.1",
      "Gmsh-exception",
      "GNAT-exception",
      "GNOME-examples-exception",
      "GNU-compiler-exception",
      "gnu-javamail-exception",
      "GPL-3.0-interface-exception",
      "GPL-3.0-linking-exception",
      "GPL-3.0-linking-source-exception",
      "GPL-CC-1.0",
      "GStreamer-exception-2005",
      "GStreamer-exception-2008",
      "i2p-gpl-java-exception",
      "KiCad-libraries-exception",
      "LGPL-3.0-linking-exception",
      "libpri-OpenH323-exception",
      "Libtool-exception",
      "Linux-syscall-note",
      "LLGPL",
      "LLVM-exception",
      "LZMA-exception",
      "mif-exception",
      "OCaml-LGPL-linking-exception",
      "OCCT-exception-1.0",
      "OpenJDK-assembly-exception-1.0",
      "openvpn-openssl-exception",
      "PS-or-PDF-font-exception-20170817",
      "QPL-1.0-INRIA-2004-exception",
      "Qt-GPL-exception-1.0",
      "Qt-LGPL-exception-1.1",
      "Qwt-exception-1.0",
      "SANE-exception",
      "SHL-2.0",
      "SHL-2.1",
      "stunnel-exception",
      "SWI-exception",
      "Swift-exception",
      "Texinfo-exception",
      "u-boot-exception-2.0",
      "UBDL-exception",
      "Universal-FOSS-exception-1.0",
      "vsftpd-openssl-exception",
      "WxWindows-exception-3.1",
      "x11vnc-openssl-exception"
    ];
  }
});

// node_modules/spdx-expression-parse/scan.js
var require_scan = __commonJS({
  "node_modules/spdx-expression-parse/scan.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var licenses = [].concat(require_spdx_license_ids()).concat(require_deprecated());
    var exceptions = require_spdx_exceptions();
    module.exports = function(source) {
      var index = 0;
      function hasMore() {
        return index < source.length;
      }
      __name(hasMore, "hasMore");
      function read(value) {
        if (value instanceof RegExp) {
          var chars = source.slice(index);
          var match = chars.match(value);
          if (match) {
            index += match[0].length;
            return match[0];
          }
        } else {
          if (source.indexOf(value, index) === index) {
            index += value.length;
            return value;
          }
        }
      }
      __name(read, "read");
      function skipWhitespace() {
        read(/[ ]*/);
      }
      __name(skipWhitespace, "skipWhitespace");
      function operator() {
        var string;
        var possibilities = ["WITH", "AND", "OR", "(", ")", ":", "+"];
        for (var i = 0; i < possibilities.length; i++) {
          string = read(possibilities[i]);
          if (string) {
            break;
          }
        }
        if (string === "+" && index > 1 && source[index - 2] === " ") {
          throw new Error("Space before `+`");
        }
        return string && {
          type: "OPERATOR",
          string
        };
      }
      __name(operator, "operator");
      function idstring() {
        return read(/[A-Za-z0-9-.]+/);
      }
      __name(idstring, "idstring");
      function expectIdstring() {
        var string = idstring();
        if (!string) {
          throw new Error("Expected idstring at offset " + index);
        }
        return string;
      }
      __name(expectIdstring, "expectIdstring");
      function documentRef() {
        if (read("DocumentRef-")) {
          var string = expectIdstring();
          return { type: "DOCUMENTREF", string };
        }
      }
      __name(documentRef, "documentRef");
      function licenseRef() {
        if (read("LicenseRef-")) {
          var string = expectIdstring();
          return { type: "LICENSEREF", string };
        }
      }
      __name(licenseRef, "licenseRef");
      function identifier() {
        var begin = index;
        var string = idstring();
        if (licenses.indexOf(string) !== -1) {
          return {
            type: "LICENSE",
            string
          };
        } else if (exceptions.indexOf(string) !== -1) {
          return {
            type: "EXCEPTION",
            string
          };
        }
        index = begin;
      }
      __name(identifier, "identifier");
      function parseToken() {
        return operator() || documentRef() || licenseRef() || identifier();
      }
      __name(parseToken, "parseToken");
      var tokens = [];
      while (hasMore()) {
        skipWhitespace();
        if (!hasMore()) {
          break;
        }
        var token = parseToken();
        if (!token) {
          throw new Error("Unexpected `" + source[index] + "` at offset " + index);
        }
        tokens.push(token);
      }
      return tokens;
    };
  }
});

// node_modules/spdx-expression-parse/parse.js
var require_parse3 = __commonJS({
  "node_modules/spdx-expression-parse/parse.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    module.exports = function(tokens) {
      var index = 0;
      function hasMore() {
        return index < tokens.length;
      }
      __name(hasMore, "hasMore");
      function token() {
        return hasMore() ? tokens[index] : null;
      }
      __name(token, "token");
      function next() {
        if (!hasMore()) {
          throw new Error();
        }
        index++;
      }
      __name(next, "next");
      function parseOperator(operator) {
        var t2 = token();
        if (t2 && t2.type === "OPERATOR" && operator === t2.string) {
          next();
          return t2.string;
        }
      }
      __name(parseOperator, "parseOperator");
      function parseWith() {
        if (parseOperator("WITH")) {
          var t2 = token();
          if (t2 && t2.type === "EXCEPTION") {
            next();
            return t2.string;
          }
          throw new Error("Expected exception after `WITH`");
        }
      }
      __name(parseWith, "parseWith");
      function parseLicenseRef() {
        var begin = index;
        var string = "";
        var t2 = token();
        if (t2.type === "DOCUMENTREF") {
          next();
          string += "DocumentRef-" + t2.string + ":";
          if (!parseOperator(":")) {
            throw new Error("Expected `:` after `DocumentRef-...`");
          }
        }
        t2 = token();
        if (t2.type === "LICENSEREF") {
          next();
          string += "LicenseRef-" + t2.string;
          return { license: string };
        }
        index = begin;
      }
      __name(parseLicenseRef, "parseLicenseRef");
      function parseLicense() {
        var t2 = token();
        if (t2 && t2.type === "LICENSE") {
          next();
          var node2 = { license: t2.string };
          if (parseOperator("+")) {
            node2.plus = true;
          }
          var exception = parseWith();
          if (exception) {
            node2.exception = exception;
          }
          return node2;
        }
      }
      __name(parseLicense, "parseLicense");
      function parseParenthesizedExpression() {
        var left = parseOperator("(");
        if (!left) {
          return;
        }
        var expr = parseExpression();
        if (!parseOperator(")")) {
          throw new Error("Expected `)`");
        }
        return expr;
      }
      __name(parseParenthesizedExpression, "parseParenthesizedExpression");
      function parseAtom() {
        return parseParenthesizedExpression() || parseLicenseRef() || parseLicense();
      }
      __name(parseAtom, "parseAtom");
      function makeBinaryOpParser(operator, nextParser) {
        return /* @__PURE__ */ __name(function parseBinaryOp() {
          var left = nextParser();
          if (!left) {
            return;
          }
          if (!parseOperator(operator)) {
            return left;
          }
          var right = parseBinaryOp();
          if (!right) {
            throw new Error("Expected expression");
          }
          return {
            left,
            conjunction: operator.toLowerCase(),
            right
          };
        }, "parseBinaryOp");
      }
      __name(makeBinaryOpParser, "makeBinaryOpParser");
      var parseAnd = makeBinaryOpParser("AND", parseAtom);
      var parseExpression = makeBinaryOpParser("OR", parseAnd);
      var node = parseExpression();
      if (!node || hasMore()) {
        throw new Error("Syntax error");
      }
      return node;
    };
  }
});

// node_modules/spdx-expression-parse/index.js
var require_spdx_expression_parse = __commonJS({
  "node_modules/spdx-expression-parse/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var scan = require_scan();
    var parse4 = require_parse3();
    module.exports = function(source) {
      return parse4(scan(source));
    };
  }
});

// node_modules/spdx-correct/index.js
var require_spdx_correct = __commonJS({
  "node_modules/spdx-correct/index.js"(exports, module) {
    init_esbuild_shims();
    var parse4 = require_spdx_expression_parse();
    var spdxLicenseIds = require_spdx_license_ids();
    function valid(string) {
      try {
        parse4(string);
        return true;
      } catch (error) {
        return false;
      }
    }
    __name(valid, "valid");
    function sortTranspositions(a, b) {
      var length = b[0].length - a[0].length;
      if (length !== 0) return length;
      return a[0].toUpperCase().localeCompare(b[0].toUpperCase());
    }
    __name(sortTranspositions, "sortTranspositions");
    var transpositions = [
      ["APGL", "AGPL"],
      ["Gpl", "GPL"],
      ["GLP", "GPL"],
      ["APL", "Apache"],
      ["ISD", "ISC"],
      ["GLP", "GPL"],
      ["IST", "ISC"],
      ["Claude", "Clause"],
      [" or later", "+"],
      [" International", ""],
      ["GNU", "GPL"],
      ["GUN", "GPL"],
      ["+", ""],
      ["GNU GPL", "GPL"],
      ["GNU LGPL", "LGPL"],
      ["GNU/GPL", "GPL"],
      ["GNU GLP", "GPL"],
      ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL"],
      ["GNU Lesser General Public License", "LGPL"],
      ["GNU LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
      ["GNU Lesser General Public License", "LGPL-2.1"],
      ["LESSER GENERAL PUBLIC LICENSE", "LGPL"],
      ["Lesser General Public License", "LGPL"],
      ["LESSER GENERAL PUBLIC LICENSE", "LGPL-2.1"],
      ["Lesser General Public License", "LGPL-2.1"],
      ["GNU General Public License", "GPL"],
      ["Gnu public license", "GPL"],
      ["GNU Public License", "GPL"],
      ["GNU GENERAL PUBLIC LICENSE", "GPL"],
      ["MTI", "MIT"],
      ["Mozilla Public License", "MPL"],
      ["Universal Permissive License", "UPL"],
      ["WTH", "WTF"],
      ["WTFGPL", "WTFPL"],
      ["-License", ""]
    ].sort(sortTranspositions);
    var TRANSPOSED = 0;
    var CORRECT = 1;
    var transforms = [
      // e.g. 'mit'
      function(argument) {
        return argument.toUpperCase();
      },
      // e.g. 'MIT '
      function(argument) {
        return argument.trim();
      },
      // e.g. 'M.I.T.'
      function(argument) {
        return argument.replace(/\./g, "");
      },
      // e.g. 'Apache- 2.0'
      function(argument) {
        return argument.replace(/\s+/g, "");
      },
      // e.g. 'CC BY 4.0''
      function(argument) {
        return argument.replace(/\s+/g, "-");
      },
      // e.g. 'LGPLv2.1'
      function(argument) {
        return argument.replace("v", "-");
      },
      // e.g. 'Apache 2.0'
      function(argument) {
        return argument.replace(/,?\s*(\d)/, "-$1");
      },
      // e.g. 'GPL 2'
      function(argument) {
        return argument.replace(/,?\s*(\d)/, "-$1.0");
      },
      // e.g. 'Apache Version 2.0'
      function(argument) {
        return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2");
      },
      // e.g. 'Apache Version 2'
      function(argument) {
        return argument.replace(/,?\s*(V\.|v\.|V|v|Version|version)\s*(\d)/, "-$2.0");
      },
      // e.g. 'ZLIB'
      function(argument) {
        return argument[0].toUpperCase() + argument.slice(1);
      },
      // e.g. 'MPL/2.0'
      function(argument) {
        return argument.replace("/", "-");
      },
      // e.g. 'Apache 2'
      function(argument) {
        return argument.replace(/\s*V\s*(\d)/, "-$1").replace(/(\d)$/, "$1.0");
      },
      // e.g. 'GPL-2.0', 'GPL-3.0'
      function(argument) {
        if (argument.indexOf("3.0") !== -1) {
          return argument + "-or-later";
        } else {
          return argument + "-only";
        }
      },
      // e.g. 'GPL-2.0-'
      function(argument) {
        return argument + "only";
      },
      // e.g. 'GPL2'
      function(argument) {
        return argument.replace(/(\d)$/, "-$1.0");
      },
      // e.g. 'BSD 3'
      function(argument) {
        return argument.replace(/(-| )?(\d)$/, "-$2-Clause");
      },
      // e.g. 'BSD clause 3'
      function(argument) {
        return argument.replace(/(-| )clause(-| )(\d)/, "-$3-Clause");
      },
      // e.g. 'New BSD license'
      function(argument) {
        return argument.replace(/\b(Modified|New|Revised)(-| )?BSD((-| )License)?/i, "BSD-3-Clause");
      },
      // e.g. 'Simplified BSD license'
      function(argument) {
        return argument.replace(/\bSimplified(-| )?BSD((-| )License)?/i, "BSD-2-Clause");
      },
      // e.g. 'Free BSD license'
      function(argument) {
        return argument.replace(/\b(Free|Net)(-| )?BSD((-| )License)?/i, "BSD-2-Clause-$1BSD");
      },
      // e.g. 'Clear BSD license'
      function(argument) {
        return argument.replace(/\bClear(-| )?BSD((-| )License)?/i, "BSD-3-Clause-Clear");
      },
      // e.g. 'Old BSD License'
      function(argument) {
        return argument.replace(/\b(Old|Original)(-| )?BSD((-| )License)?/i, "BSD-4-Clause");
      },
      // e.g. 'BY-NC-4.0'
      function(argument) {
        return "CC-" + argument;
      },
      // e.g. 'BY-NC'
      function(argument) {
        return "CC-" + argument + "-4.0";
      },
      // e.g. 'Attribution-NonCommercial'
      function(argument) {
        return argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "");
      },
      // e.g. 'Attribution-NonCommercial'
      function(argument) {
        return "CC-" + argument.replace("Attribution", "BY").replace("NonCommercial", "NC").replace("NoDerivatives", "ND").replace(/ (\d)/, "-$1").replace(/ ?International/, "") + "-4.0";
      }
    ];
    var licensesWithVersions = spdxLicenseIds.map(function(id) {
      var match = /^(.*)-\d+\.\d+$/.exec(id);
      return match ? [match[0], match[1]] : [id, null];
    }).reduce(function(objectMap, item) {
      var key = item[1];
      objectMap[key] = objectMap[key] || [];
      objectMap[key].push(item[0]);
      return objectMap;
    }, {});
    var licensesWithOneVersion = Object.keys(licensesWithVersions).map(/* @__PURE__ */ __name(function makeEntries(key) {
      return [key, licensesWithVersions[key]];
    }, "makeEntries")).filter(/* @__PURE__ */ __name(function identifySoleVersions(item) {
      return (
        // Licenses has just one valid version suffix.
        item[1].length === 1 && item[0] !== null && // APL will be considered Apache, rather than APL-1.0
        item[0] !== "APL"
      );
    }, "identifySoleVersions")).map(/* @__PURE__ */ __name(function createLastResorts(item) {
      return [item[0], item[1][0]];
    }, "createLastResorts"));
    licensesWithVersions = void 0;
    var lastResorts = [
      ["UNLI", "Unlicense"],
      ["WTF", "WTFPL"],
      ["2 CLAUSE", "BSD-2-Clause"],
      ["2-CLAUSE", "BSD-2-Clause"],
      ["3 CLAUSE", "BSD-3-Clause"],
      ["3-CLAUSE", "BSD-3-Clause"],
      ["AFFERO", "AGPL-3.0-or-later"],
      ["AGPL", "AGPL-3.0-or-later"],
      ["APACHE", "Apache-2.0"],
      ["ARTISTIC", "Artistic-2.0"],
      ["Affero", "AGPL-3.0-or-later"],
      ["BEER", "Beerware"],
      ["BOOST", "BSL-1.0"],
      ["BSD", "BSD-2-Clause"],
      ["CDDL", "CDDL-1.1"],
      ["ECLIPSE", "EPL-1.0"],
      ["FUCK", "WTFPL"],
      ["GNU", "GPL-3.0-or-later"],
      ["LGPL", "LGPL-3.0-or-later"],
      ["GPLV1", "GPL-1.0-only"],
      ["GPL-1", "GPL-1.0-only"],
      ["GPLV2", "GPL-2.0-only"],
      ["GPL-2", "GPL-2.0-only"],
      ["GPL", "GPL-3.0-or-later"],
      ["MIT +NO-FALSE-ATTRIBS", "MITNFA"],
      ["MIT", "MIT"],
      ["MPL", "MPL-2.0"],
      ["X11", "X11"],
      ["ZLIB", "Zlib"]
    ].concat(licensesWithOneVersion).sort(sortTranspositions);
    var SUBSTRING = 0;
    var IDENTIFIER = 1;
    var validTransformation = /* @__PURE__ */ __name(function(identifier) {
      for (var i = 0; i < transforms.length; i++) {
        var transformed = transforms[i](identifier).trim();
        if (transformed !== identifier && valid(transformed)) {
          return transformed;
        }
      }
      return null;
    }, "validTransformation");
    var validLastResort = /* @__PURE__ */ __name(function(identifier) {
      var upperCased = identifier.toUpperCase();
      for (var i = 0; i < lastResorts.length; i++) {
        var lastResort = lastResorts[i];
        if (upperCased.indexOf(lastResort[SUBSTRING]) > -1) {
          return lastResort[IDENTIFIER];
        }
      }
      return null;
    }, "validLastResort");
    var anyCorrection = /* @__PURE__ */ __name(function(identifier, check) {
      for (var i = 0; i < transpositions.length; i++) {
        var transposition = transpositions[i];
        var transposed = transposition[TRANSPOSED];
        if (identifier.indexOf(transposed) > -1) {
          var corrected = identifier.replace(
            transposed,
            transposition[CORRECT]
          );
          var checked = check(corrected);
          if (checked !== null) {
            return checked;
          }
        }
      }
      return null;
    }, "anyCorrection");
    module.exports = function(identifier, options) {
      options = options || {};
      var upgrade = options.upgrade === void 0 ? true : !!options.upgrade;
      function postprocess(value) {
        return upgrade ? upgradeGPLs(value) : value;
      }
      __name(postprocess, "postprocess");
      var validArugment = typeof identifier === "string" && identifier.trim().length !== 0;
      if (!validArugment) {
        throw Error("Invalid argument. Expected non-empty string.");
      }
      identifier = identifier.trim();
      if (valid(identifier)) {
        return postprocess(identifier);
      }
      var noPlus = identifier.replace(/\+$/, "").trim();
      if (valid(noPlus)) {
        return postprocess(noPlus);
      }
      var transformed = validTransformation(identifier);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = anyCorrection(identifier, function(argument) {
        if (valid(argument)) {
          return argument;
        }
        return validTransformation(argument);
      });
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = validLastResort(identifier);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      transformed = anyCorrection(identifier, validLastResort);
      if (transformed !== null) {
        return postprocess(transformed);
      }
      return null;
    };
    function upgradeGPLs(value) {
      if ([
        "GPL-1.0",
        "LGPL-1.0",
        "AGPL-1.0",
        "GPL-2.0",
        "LGPL-2.0",
        "AGPL-2.0",
        "LGPL-2.1"
      ].indexOf(value) !== -1) {
        return value + "-only";
      } else if ([
        "GPL-1.0+",
        "GPL-2.0+",
        "GPL-3.0+",
        "LGPL-2.0+",
        "LGPL-2.1+",
        "LGPL-3.0+",
        "AGPL-1.0+",
        "AGPL-3.0+"
      ].indexOf(value) !== -1) {
        return value.replace(/\+$/, "-or-later");
      } else if (["GPL-3.0", "LGPL-3.0", "AGPL-3.0"].indexOf(value) !== -1) {
        return value + "-or-later";
      } else {
        return value;
      }
    }
    __name(upgradeGPLs, "upgradeGPLs");
  }
});

// node_modules/validate-npm-package-license/index.js
var require_validate_npm_package_license = __commonJS({
  "node_modules/validate-npm-package-license/index.js"(exports, module) {
    init_esbuild_shims();
    var parse4 = require_spdx_expression_parse();
    var correct = require_spdx_correct();
    var genericWarning = 'license should be a valid SPDX license expression (without "LicenseRef"), "UNLICENSED", or "SEE LICENSE IN <filename>"';
    var fileReferenceRE = /^SEE LICEN[CS]E IN (.+)$/;
    function startsWith(prefix, string) {
      return string.slice(0, prefix.length) === prefix;
    }
    __name(startsWith, "startsWith");
    function usesLicenseRef(ast) {
      if (ast.hasOwnProperty("license")) {
        var license = ast.license;
        return startsWith("LicenseRef", license) || startsWith("DocumentRef", license);
      } else {
        return usesLicenseRef(ast.left) || usesLicenseRef(ast.right);
      }
    }
    __name(usesLicenseRef, "usesLicenseRef");
    module.exports = function(argument) {
      var ast;
      try {
        ast = parse4(argument);
      } catch (e) {
        var match;
        if (argument === "UNLICENSED" || argument === "UNLICENCED") {
          return {
            validForOldPackages: true,
            validForNewPackages: true,
            unlicensed: true
          };
        } else if (match = fileReferenceRE.exec(argument)) {
          return {
            validForOldPackages: true,
            validForNewPackages: true,
            inFile: match[1]
          };
        } else {
          var result = {
            validForOldPackages: false,
            validForNewPackages: false,
            warnings: [genericWarning]
          };
          if (argument.trim().length !== 0) {
            var corrected = correct(argument);
            if (corrected) {
              result.warnings.push(
                'license is similar to the valid expression "' + corrected + '"'
              );
            }
          }
          return result;
        }
      }
      if (usesLicenseRef(ast)) {
        return {
          validForNewPackages: false,
          validForOldPackages: false,
          spdx: true,
          warnings: [genericWarning]
        };
      } else {
        return {
          validForNewPackages: true,
          validForOldPackages: true,
          spdx: true
        };
      }
    };
  }
});

// node_modules/lru-cache/dist/commonjs/index.js
var require_commonjs = __commonJS({
  "node_modules/lru-cache/dist/commonjs/index.js"(exports) {
    "use strict";
    init_esbuild_shims();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.LRUCache = void 0;
    var perf = typeof performance === "object" && performance && typeof performance.now === "function" ? performance : Date;
    var warned = /* @__PURE__ */ new Set();
    var PROCESS = typeof process === "object" && !!process ? process : {};
    var emitWarning = /* @__PURE__ */ __name((msg, type, code, fn) => {
      typeof PROCESS.emitWarning === "function" ? PROCESS.emitWarning(msg, type, code, fn) : console.error(`[${code}] ${type}: ${msg}`);
    }, "emitWarning");
    var AC = globalThis.AbortController;
    var AS = globalThis.AbortSignal;
    if (typeof AC === "undefined") {
      AS = class AbortSignal {
        static {
          __name(this, "AbortSignal");
        }
        onabort;
        _onabort = [];
        reason;
        aborted = false;
        addEventListener(_, fn) {
          this._onabort.push(fn);
        }
      };
      AC = class AbortController {
        static {
          __name(this, "AbortController");
        }
        constructor() {
          warnACPolyfill();
        }
        signal = new AS();
        abort(reason) {
          if (this.signal.aborted)
            return;
          this.signal.reason = reason;
          this.signal.aborted = true;
          for (const fn of this.signal._onabort) {
            fn(reason);
          }
          this.signal.onabort?.(reason);
        }
      };
      let printACPolyfillWarning = PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1";
      const warnACPolyfill = /* @__PURE__ */ __name(() => {
        if (!printACPolyfillWarning)
          return;
        printACPolyfillWarning = false;
        emitWarning("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", warnACPolyfill);
      }, "warnACPolyfill");
    }
    var shouldWarn = /* @__PURE__ */ __name((code) => !warned.has(code), "shouldWarn");
    var TYPE = Symbol("type");
    var isPosInt = /* @__PURE__ */ __name((n) => n && n === Math.floor(n) && n > 0 && isFinite(n), "isPosInt");
    var getUintArray = /* @__PURE__ */ __name((max) => !isPosInt(max) ? null : max <= Math.pow(2, 8) ? Uint8Array : max <= Math.pow(2, 16) ? Uint16Array : max <= Math.pow(2, 32) ? Uint32Array : max <= Number.MAX_SAFE_INTEGER ? ZeroArray : null, "getUintArray");
    var ZeroArray = class extends Array {
      static {
        __name(this, "ZeroArray");
      }
      constructor(size) {
        super(size);
        this.fill(0);
      }
    };
    var Stack = class _Stack {
      static {
        __name(this, "Stack");
      }
      heap;
      length;
      // private constructor
      static #constructing = false;
      static create(max) {
        const HeapCls = getUintArray(max);
        if (!HeapCls)
          return [];
        _Stack.#constructing = true;
        const s = new _Stack(max, HeapCls);
        _Stack.#constructing = false;
        return s;
      }
      constructor(max, HeapCls) {
        if (!_Stack.#constructing) {
          throw new TypeError("instantiate Stack using Stack.create(n)");
        }
        this.heap = new HeapCls(max);
        this.length = 0;
      }
      push(n) {
        this.heap[this.length++] = n;
      }
      pop() {
        return this.heap[--this.length];
      }
    };
    var LRUCache = class _LRUCache {
      static {
        __name(this, "LRUCache");
      }
      // options that cannot be changed without disaster
      #max;
      #maxSize;
      #dispose;
      #disposeAfter;
      #fetchMethod;
      #memoMethod;
      /**
       * {@link LRUCache.OptionsBase.ttl}
       */
      ttl;
      /**
       * {@link LRUCache.OptionsBase.ttlResolution}
       */
      ttlResolution;
      /**
       * {@link LRUCache.OptionsBase.ttlAutopurge}
       */
      ttlAutopurge;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnGet}
       */
      updateAgeOnGet;
      /**
       * {@link LRUCache.OptionsBase.updateAgeOnHas}
       */
      updateAgeOnHas;
      /**
       * {@link LRUCache.OptionsBase.allowStale}
       */
      allowStale;
      /**
       * {@link LRUCache.OptionsBase.noDisposeOnSet}
       */
      noDisposeOnSet;
      /**
       * {@link LRUCache.OptionsBase.noUpdateTTL}
       */
      noUpdateTTL;
      /**
       * {@link LRUCache.OptionsBase.maxEntrySize}
       */
      maxEntrySize;
      /**
       * {@link LRUCache.OptionsBase.sizeCalculation}
       */
      sizeCalculation;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}
       */
      noDeleteOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}
       */
      noDeleteOnStaleGet;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}
       */
      allowStaleOnFetchAbort;
      /**
       * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}
       */
      allowStaleOnFetchRejection;
      /**
       * {@link LRUCache.OptionsBase.ignoreFetchAbort}
       */
      ignoreFetchAbort;
      // computed properties
      #size;
      #calculatedSize;
      #keyMap;
      #keyList;
      #valList;
      #next;
      #prev;
      #head;
      #tail;
      #free;
      #disposed;
      #sizes;
      #starts;
      #ttls;
      #hasDispose;
      #hasFetchMethod;
      #hasDisposeAfter;
      /**
       * Do not call this method unless you need to inspect the
       * inner workings of the cache.  If anything returned by this
       * object is modified in any way, strange breakage may occur.
       *
       * These fields are private for a reason!
       *
       * @internal
       */
      static unsafeExposeInternals(c) {
        return {
          // properties
          starts: c.#starts,
          ttls: c.#ttls,
          sizes: c.#sizes,
          keyMap: c.#keyMap,
          keyList: c.#keyList,
          valList: c.#valList,
          next: c.#next,
          prev: c.#prev,
          get head() {
            return c.#head;
          },
          get tail() {
            return c.#tail;
          },
          free: c.#free,
          // methods
          isBackgroundFetch: /* @__PURE__ */ __name((p) => c.#isBackgroundFetch(p), "isBackgroundFetch"),
          backgroundFetch: /* @__PURE__ */ __name((k, index, options, context) => c.#backgroundFetch(k, index, options, context), "backgroundFetch"),
          moveToTail: /* @__PURE__ */ __name((index) => c.#moveToTail(index), "moveToTail"),
          indexes: /* @__PURE__ */ __name((options) => c.#indexes(options), "indexes"),
          rindexes: /* @__PURE__ */ __name((options) => c.#rindexes(options), "rindexes"),
          isStale: /* @__PURE__ */ __name((index) => c.#isStale(index), "isStale")
        };
      }
      // Protected read-only members
      /**
       * {@link LRUCache.OptionsBase.max} (read-only)
       */
      get max() {
        return this.#max;
      }
      /**
       * {@link LRUCache.OptionsBase.maxSize} (read-only)
       */
      get maxSize() {
        return this.#maxSize;
      }
      /**
       * The total computed size of items in the cache (read-only)
       */
      get calculatedSize() {
        return this.#calculatedSize;
      }
      /**
       * The number of items stored in the cache (read-only)
       */
      get size() {
        return this.#size;
      }
      /**
       * {@link LRUCache.OptionsBase.fetchMethod} (read-only)
       */
      get fetchMethod() {
        return this.#fetchMethod;
      }
      get memoMethod() {
        return this.#memoMethod;
      }
      /**
       * {@link LRUCache.OptionsBase.dispose} (read-only)
       */
      get dispose() {
        return this.#dispose;
      }
      /**
       * {@link LRUCache.OptionsBase.disposeAfter} (read-only)
       */
      get disposeAfter() {
        return this.#disposeAfter;
      }
      constructor(options) {
        const { max = 0, ttl, ttlResolution = 1, ttlAutopurge, updateAgeOnGet, updateAgeOnHas, allowStale, dispose, disposeAfter, noDisposeOnSet, noUpdateTTL, maxSize = 0, maxEntrySize = 0, sizeCalculation, fetchMethod, memoMethod, noDeleteOnFetchRejection, noDeleteOnStaleGet, allowStaleOnFetchRejection, allowStaleOnFetchAbort, ignoreFetchAbort } = options;
        if (max !== 0 && !isPosInt(max)) {
          throw new TypeError("max option must be a nonnegative integer");
        }
        const UintArray = max ? getUintArray(max) : Array;
        if (!UintArray) {
          throw new Error("invalid max value: " + max);
        }
        this.#max = max;
        this.#maxSize = maxSize;
        this.maxEntrySize = maxEntrySize || this.#maxSize;
        this.sizeCalculation = sizeCalculation;
        if (this.sizeCalculation) {
          if (!this.#maxSize && !this.maxEntrySize) {
            throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
          }
          if (typeof this.sizeCalculation !== "function") {
            throw new TypeError("sizeCalculation set to non-function");
          }
        }
        if (memoMethod !== void 0 && typeof memoMethod !== "function") {
          throw new TypeError("memoMethod must be a function if defined");
        }
        this.#memoMethod = memoMethod;
        if (fetchMethod !== void 0 && typeof fetchMethod !== "function") {
          throw new TypeError("fetchMethod must be a function if specified");
        }
        this.#fetchMethod = fetchMethod;
        this.#hasFetchMethod = !!fetchMethod;
        this.#keyMap = /* @__PURE__ */ new Map();
        this.#keyList = new Array(max).fill(void 0);
        this.#valList = new Array(max).fill(void 0);
        this.#next = new UintArray(max);
        this.#prev = new UintArray(max);
        this.#head = 0;
        this.#tail = 0;
        this.#free = Stack.create(max);
        this.#size = 0;
        this.#calculatedSize = 0;
        if (typeof dispose === "function") {
          this.#dispose = dispose;
        }
        if (typeof disposeAfter === "function") {
          this.#disposeAfter = disposeAfter;
          this.#disposed = [];
        } else {
          this.#disposeAfter = void 0;
          this.#disposed = void 0;
        }
        this.#hasDispose = !!this.#dispose;
        this.#hasDisposeAfter = !!this.#disposeAfter;
        this.noDisposeOnSet = !!noDisposeOnSet;
        this.noUpdateTTL = !!noUpdateTTL;
        this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection;
        this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection;
        this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort;
        this.ignoreFetchAbort = !!ignoreFetchAbort;
        if (this.maxEntrySize !== 0) {
          if (this.#maxSize !== 0) {
            if (!isPosInt(this.#maxSize)) {
              throw new TypeError("maxSize must be a positive integer if specified");
            }
          }
          if (!isPosInt(this.maxEntrySize)) {
            throw new TypeError("maxEntrySize must be a positive integer if specified");
          }
          this.#initializeSizeTracking();
        }
        this.allowStale = !!allowStale;
        this.noDeleteOnStaleGet = !!noDeleteOnStaleGet;
        this.updateAgeOnGet = !!updateAgeOnGet;
        this.updateAgeOnHas = !!updateAgeOnHas;
        this.ttlResolution = isPosInt(ttlResolution) || ttlResolution === 0 ? ttlResolution : 1;
        this.ttlAutopurge = !!ttlAutopurge;
        this.ttl = ttl || 0;
        if (this.ttl) {
          if (!isPosInt(this.ttl)) {
            throw new TypeError("ttl must be a positive integer if specified");
          }
          this.#initializeTTLTracking();
        }
        if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {
          throw new TypeError("At least one of max, maxSize, or ttl is required");
        }
        if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {
          const code = "LRU_CACHE_UNBOUNDED";
          if (shouldWarn(code)) {
            warned.add(code);
            const msg = "TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.";
            emitWarning(msg, "UnboundedCacheWarning", code, _LRUCache);
          }
        }
      }
      /**
       * Return the number of ms left in the item's TTL. If item is not in cache,
       * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.
       */
      getRemainingTTL(key) {
        return this.#keyMap.has(key) ? Infinity : 0;
      }
      #initializeTTLTracking() {
        const ttls = new ZeroArray(this.#max);
        const starts = new ZeroArray(this.#max);
        this.#ttls = ttls;
        this.#starts = starts;
        this.#setItemTTL = (index, ttl, start = perf.now()) => {
          starts[index] = ttl !== 0 ? start : 0;
          ttls[index] = ttl;
          if (ttl !== 0 && this.ttlAutopurge) {
            const t2 = setTimeout(() => {
              if (this.#isStale(index)) {
                this.#delete(this.#keyList[index], "expire");
              }
            }, ttl + 1);
            if (t2.unref) {
              t2.unref();
            }
          }
        };
        this.#updateItemAge = (index) => {
          starts[index] = ttls[index] !== 0 ? perf.now() : 0;
        };
        this.#statusTTL = (status, index) => {
          if (ttls[index]) {
            const ttl = ttls[index];
            const start = starts[index];
            if (!ttl || !start)
              return;
            status.ttl = ttl;
            status.start = start;
            status.now = cachedNow || getNow();
            const age = status.now - start;
            status.remainingTTL = ttl - age;
          }
        };
        let cachedNow = 0;
        const getNow = /* @__PURE__ */ __name(() => {
          const n = perf.now();
          if (this.ttlResolution > 0) {
            cachedNow = n;
            const t2 = setTimeout(() => cachedNow = 0, this.ttlResolution);
            if (t2.unref) {
              t2.unref();
            }
          }
          return n;
        }, "getNow");
        this.getRemainingTTL = (key) => {
          const index = this.#keyMap.get(key);
          if (index === void 0) {
            return 0;
          }
          const ttl = ttls[index];
          const start = starts[index];
          if (!ttl || !start) {
            return Infinity;
          }
          const age = (cachedNow || getNow()) - start;
          return ttl - age;
        };
        this.#isStale = (index) => {
          const s = starts[index];
          const t2 = ttls[index];
          return !!t2 && !!s && (cachedNow || getNow()) - s > t2;
        };
      }
      // conditionally set private methods related to TTL
      #updateItemAge = /* @__PURE__ */ __name(() => {
      }, "#updateItemAge");
      #statusTTL = /* @__PURE__ */ __name(() => {
      }, "#statusTTL");
      #setItemTTL = /* @__PURE__ */ __name(() => {
      }, "#setItemTTL");
      /* c8 ignore stop */
      #isStale = /* @__PURE__ */ __name(() => false, "#isStale");
      #initializeSizeTracking() {
        const sizes = new ZeroArray(this.#max);
        this.#calculatedSize = 0;
        this.#sizes = sizes;
        this.#removeItemSize = (index) => {
          this.#calculatedSize -= sizes[index];
          sizes[index] = 0;
        };
        this.#requireSize = (k, v, size, sizeCalculation) => {
          if (this.#isBackgroundFetch(v)) {
            return 0;
          }
          if (!isPosInt(size)) {
            if (sizeCalculation) {
              if (typeof sizeCalculation !== "function") {
                throw new TypeError("sizeCalculation must be a function");
              }
              size = sizeCalculation(v, k);
              if (!isPosInt(size)) {
                throw new TypeError("sizeCalculation return invalid (expect positive integer)");
              }
            } else {
              throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
            }
          }
          return size;
        };
        this.#addItemSize = (index, size, status) => {
          sizes[index] = size;
          if (this.#maxSize) {
            const maxSize = this.#maxSize - sizes[index];
            while (this.#calculatedSize > maxSize) {
              this.#evict(true);
            }
          }
          this.#calculatedSize += sizes[index];
          if (status) {
            status.entrySize = size;
            status.totalCalculatedSize = this.#calculatedSize;
          }
        };
      }
      #removeItemSize = /* @__PURE__ */ __name((_i) => {
      }, "#removeItemSize");
      #addItemSize = /* @__PURE__ */ __name((_i, _s, _st) => {
      }, "#addItemSize");
      #requireSize = /* @__PURE__ */ __name((_k, _v, size, sizeCalculation) => {
        if (size || sizeCalculation) {
          throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
        }
        return 0;
      }, "#requireSize");
      *#indexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#tail; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#head) {
              break;
            } else {
              i = this.#prev[i];
            }
          }
        }
      }
      *#rindexes({ allowStale = this.allowStale } = {}) {
        if (this.#size) {
          for (let i = this.#head; true; ) {
            if (!this.#isValidIndex(i)) {
              break;
            }
            if (allowStale || !this.#isStale(i)) {
              yield i;
            }
            if (i === this.#tail) {
              break;
            } else {
              i = this.#next[i];
            }
          }
        }
      }
      #isValidIndex(index) {
        return index !== void 0 && this.#keyMap.get(this.#keyList[index]) === index;
      }
      /**
       * Return a generator yielding `[key, value]` pairs,
       * in order from most recently used to least recently used.
       */
      *entries() {
        for (const i of this.#indexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.entries}
       *
       * Return a generator yielding `[key, value]` pairs,
       * in order from least recently used to most recently used.
       */
      *rentries() {
        for (const i of this.#rindexes()) {
          if (this.#valList[i] !== void 0 && this.#keyList[i] !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield [this.#keyList[i], this.#valList[i]];
          }
        }
      }
      /**
       * Return a generator yielding the keys in the cache,
       * in order from most recently used to least recently used.
       */
      *keys() {
        for (const i of this.#indexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.keys}
       *
       * Return a generator yielding the keys in the cache,
       * in order from least recently used to most recently used.
       */
      *rkeys() {
        for (const i of this.#rindexes()) {
          const k = this.#keyList[i];
          if (k !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield k;
          }
        }
      }
      /**
       * Return a generator yielding the values in the cache,
       * in order from most recently used to least recently used.
       */
      *values() {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Inverse order version of {@link LRUCache.values}
       *
       * Return a generator yielding the values in the cache,
       * in order from least recently used to most recently used.
       */
      *rvalues() {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          if (v !== void 0 && !this.#isBackgroundFetch(this.#valList[i])) {
            yield this.#valList[i];
          }
        }
      }
      /**
       * Iterating over the cache itself yields the same results as
       * {@link LRUCache.entries}
       */
      [Symbol.iterator]() {
        return this.entries();
      }
      /**
       * A String value that is used in the creation of the default string
       * description of an object. Called by the built-in method
       * `Object.prototype.toString`.
       */
      [Symbol.toStringTag] = "LRUCache";
      /**
       * Find a value for which the supplied fn method returns a truthy value,
       * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.
       */
      find(fn, getOptions = {}) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          if (fn(value, this.#keyList[i], this)) {
            return this.get(this.#keyList[i], getOptions);
          }
        }
      }
      /**
       * Call the supplied function on each item in the cache, in order from most
       * recently used to least recently used.
       *
       * `fn` is called as `fn(value, key, cache)`.
       *
       * If `thisp` is provided, function will be called in the `this`-context of
       * the provided object, or the cache if no `thisp` object is provided.
       *
       * Does not update age or recenty of use, or iterate over stale values.
       */
      forEach(fn, thisp = this) {
        for (const i of this.#indexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * The same as {@link LRUCache.forEach} but items are iterated over in
       * reverse order.  (ie, less recently used items are iterated over first.)
       */
      rforEach(fn, thisp = this) {
        for (const i of this.#rindexes()) {
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0)
            continue;
          fn.call(thisp, value, this.#keyList[i], this);
        }
      }
      /**
       * Delete any stale entries. Returns true if anything was removed,
       * false otherwise.
       */
      purgeStale() {
        let deleted = false;
        for (const i of this.#rindexes({ allowStale: true })) {
          if (this.#isStale(i)) {
            this.#delete(this.#keyList[i], "expire");
            deleted = true;
          }
        }
        return deleted;
      }
      /**
       * Get the extended info about a given entry, to get its value, size, and
       * TTL info simultaneously. Returns `undefined` if the key is not present.
       *
       * Unlike {@link LRUCache#dump}, which is designed to be portable and survive
       * serialization, the `start` value is always the current timestamp, and the
       * `ttl` is a calculated remaining time to live (negative if expired).
       *
       * Always returns stale values, if their info is found in the cache, so be
       * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})
       * if relevant.
       */
      info(key) {
        const i = this.#keyMap.get(key);
        if (i === void 0)
          return void 0;
        const v = this.#valList[i];
        const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
        if (value === void 0)
          return void 0;
        const entry = { value };
        if (this.#ttls && this.#starts) {
          const ttl = this.#ttls[i];
          const start = this.#starts[i];
          if (ttl && start) {
            const remain = ttl - (perf.now() - start);
            entry.ttl = remain;
            entry.start = Date.now();
          }
        }
        if (this.#sizes) {
          entry.size = this.#sizes[i];
        }
        return entry;
      }
      /**
       * Return an array of [key, {@link LRUCache.Entry}] tuples which can be
       * passed to {@link LRLUCache#load}.
       *
       * The `start` fields are calculated relative to a portable `Date.now()`
       * timestamp, even if `performance.now()` is available.
       *
       * Stale entries are always included in the `dump`, even if
       * {@link LRUCache.OptionsBase.allowStale} is false.
       *
       * Note: this returns an actual array, not a generator, so it can be more
       * easily passed around.
       */
      dump() {
        const arr = [];
        for (const i of this.#indexes({ allowStale: true })) {
          const key = this.#keyList[i];
          const v = this.#valList[i];
          const value = this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
          if (value === void 0 || key === void 0)
            continue;
          const entry = { value };
          if (this.#ttls && this.#starts) {
            entry.ttl = this.#ttls[i];
            const age = perf.now() - this.#starts[i];
            entry.start = Math.floor(Date.now() - age);
          }
          if (this.#sizes) {
            entry.size = this.#sizes[i];
          }
          arr.unshift([key, entry]);
        }
        return arr;
      }
      /**
       * Reset the cache and load in the items in entries in the order listed.
       *
       * The shape of the resulting cache may be different if the same options are
       * not used in both caches.
       *
       * The `start` fields are assumed to be calculated relative to a portable
       * `Date.now()` timestamp, even if `performance.now()` is available.
       */
      load(arr) {
        this.clear();
        for (const [key, entry] of arr) {
          if (entry.start) {
            const age = Date.now() - entry.start;
            entry.start = perf.now() - age;
          }
          this.set(key, entry.value, entry);
        }
      }
      /**
       * Add a value to the cache.
       *
       * Note: if `undefined` is specified as a value, this is an alias for
       * {@link LRUCache#delete}
       *
       * Fields on the {@link LRUCache.SetOptions} options param will override
       * their corresponding values in the constructor options for the scope
       * of this single `set()` operation.
       *
       * If `start` is provided, then that will set the effective start
       * time for the TTL calculation. Note that this must be a previous
       * value of `performance.now()` if supported, or a previous value of
       * `Date.now()` if not.
       *
       * Options object may also include `size`, which will prevent
       * calling the `sizeCalculation` function and just use the specified
       * number if it is a positive integer, and `noDisposeOnSet` which
       * will prevent calling a `dispose` function in the case of
       * overwrites.
       *
       * If the `size` (or return value of `sizeCalculation`) for a given
       * entry is greater than `maxEntrySize`, then the item will not be
       * added to the cache.
       *
       * Will update the recency of the entry.
       *
       * If the value is `undefined`, then this is an alias for
       * `cache.delete(key)`. `undefined` is never stored in the cache.
       */
      set(k, v, setOptions = {}) {
        if (v === void 0) {
          this.delete(k);
          return this;
        }
        const { ttl = this.ttl, start, noDisposeOnSet = this.noDisposeOnSet, sizeCalculation = this.sizeCalculation, status } = setOptions;
        let { noUpdateTTL = this.noUpdateTTL } = setOptions;
        const size = this.#requireSize(k, v, setOptions.size || 0, sizeCalculation);
        if (this.maxEntrySize && size > this.maxEntrySize) {
          if (status) {
            status.set = "miss";
            status.maxEntrySizeExceeded = true;
          }
          this.#delete(k, "set");
          return this;
        }
        let index = this.#size === 0 ? void 0 : this.#keyMap.get(k);
        if (index === void 0) {
          index = this.#size === 0 ? this.#tail : this.#free.length !== 0 ? this.#free.pop() : this.#size === this.#max ? this.#evict(false) : this.#size;
          this.#keyList[index] = k;
          this.#valList[index] = v;
          this.#keyMap.set(k, index);
          this.#next[this.#tail] = index;
          this.#prev[index] = this.#tail;
          this.#tail = index;
          this.#size++;
          this.#addItemSize(index, size, status);
          if (status)
            status.set = "add";
          noUpdateTTL = false;
        } else {
          this.#moveToTail(index);
          const oldVal = this.#valList[index];
          if (v !== oldVal) {
            if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {
              oldVal.__abortController.abort(new Error("replaced"));
              const { __staleWhileFetching: s } = oldVal;
              if (s !== void 0 && !noDisposeOnSet) {
                if (this.#hasDispose) {
                  this.#dispose?.(s, k, "set");
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([s, k, "set"]);
                }
              }
            } else if (!noDisposeOnSet) {
              if (this.#hasDispose) {
                this.#dispose?.(oldVal, k, "set");
              }
              if (this.#hasDisposeAfter) {
                this.#disposed?.push([oldVal, k, "set"]);
              }
            }
            this.#removeItemSize(index);
            this.#addItemSize(index, size, status);
            this.#valList[index] = v;
            if (status) {
              status.set = "replace";
              const oldValue = oldVal && this.#isBackgroundFetch(oldVal) ? oldVal.__staleWhileFetching : oldVal;
              if (oldValue !== void 0)
                status.oldValue = oldValue;
            }
          } else if (status) {
            status.set = "update";
          }
        }
        if (ttl !== 0 && !this.#ttls) {
          this.#initializeTTLTracking();
        }
        if (this.#ttls) {
          if (!noUpdateTTL) {
            this.#setItemTTL(index, ttl, start);
          }
          if (status)
            this.#statusTTL(status, index);
        }
        if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return this;
      }
      /**
       * Evict the least recently used item, returning its value or
       * `undefined` if cache is empty.
       */
      pop() {
        try {
          while (this.#size) {
            const val = this.#valList[this.#head];
            this.#evict(true);
            if (this.#isBackgroundFetch(val)) {
              if (val.__staleWhileFetching) {
                return val.__staleWhileFetching;
              }
            } else if (val !== void 0) {
              return val;
            }
          }
        } finally {
          if (this.#hasDisposeAfter && this.#disposed) {
            const dt = this.#disposed;
            let task;
            while (task = dt?.shift()) {
              this.#disposeAfter?.(...task);
            }
          }
        }
      }
      #evict(free) {
        const head = this.#head;
        const k = this.#keyList[head];
        const v = this.#valList[head];
        if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {
          v.__abortController.abort(new Error("evicted"));
        } else if (this.#hasDispose || this.#hasDisposeAfter) {
          if (this.#hasDispose) {
            this.#dispose?.(v, k, "evict");
          }
          if (this.#hasDisposeAfter) {
            this.#disposed?.push([v, k, "evict"]);
          }
        }
        this.#removeItemSize(head);
        if (free) {
          this.#keyList[head] = void 0;
          this.#valList[head] = void 0;
          this.#free.push(head);
        }
        if (this.#size === 1) {
          this.#head = this.#tail = 0;
          this.#free.length = 0;
        } else {
          this.#head = this.#next[head];
        }
        this.#keyMap.delete(k);
        this.#size--;
        return head;
      }
      /**
       * Check if a key is in the cache, without updating the recency of use.
       * Will return false if the item is stale, even though it is technically
       * in the cache.
       *
       * Check if a key is in the cache, without updating the recency of
       * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set
       * to `true` in either the options or the constructor.
       *
       * Will return `false` if the item is stale, even though it is technically in
       * the cache. The difference can be determined (if it matters) by using a
       * `status` argument, and inspecting the `has` field.
       *
       * Will not update item age unless
       * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.
       */
      has(k, hasOptions = {}) {
        const { updateAgeOnHas = this.updateAgeOnHas, status } = hasOptions;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v) && v.__staleWhileFetching === void 0) {
            return false;
          }
          if (!this.#isStale(index)) {
            if (updateAgeOnHas) {
              this.#updateItemAge(index);
            }
            if (status) {
              status.has = "hit";
              this.#statusTTL(status, index);
            }
            return true;
          } else if (status) {
            status.has = "stale";
            this.#statusTTL(status, index);
          }
        } else if (status) {
          status.has = "miss";
        }
        return false;
      }
      /**
       * Like {@link LRUCache#get} but doesn't update recency or delete stale
       * items.
       *
       * Returns `undefined` if the item is stale, unless
       * {@link LRUCache.OptionsBase.allowStale} is set.
       */
      peek(k, peekOptions = {}) {
        const { allowStale = this.allowStale } = peekOptions;
        const index = this.#keyMap.get(k);
        if (index === void 0 || !allowStale && this.#isStale(index)) {
          return;
        }
        const v = this.#valList[index];
        return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v;
      }
      #backgroundFetch(k, index, options, context) {
        const v = index === void 0 ? void 0 : this.#valList[index];
        if (this.#isBackgroundFetch(v)) {
          return v;
        }
        const ac = new AC();
        const { signal } = options;
        signal?.addEventListener("abort", () => ac.abort(signal.reason), {
          signal: ac.signal
        });
        const fetchOpts = {
          signal: ac.signal,
          options,
          context
        };
        const cb = /* @__PURE__ */ __name((v2, updateCache = false) => {
          const { aborted } = ac.signal;
          const ignoreAbort = options.ignoreFetchAbort && v2 !== void 0;
          if (options.status) {
            if (aborted && !updateCache) {
              options.status.fetchAborted = true;
              options.status.fetchError = ac.signal.reason;
              if (ignoreAbort)
                options.status.fetchAbortIgnored = true;
            } else {
              options.status.fetchResolved = true;
            }
          }
          if (aborted && !ignoreAbort && !updateCache) {
            return fetchFail(ac.signal.reason);
          }
          const bf2 = p;
          if (this.#valList[index] === p) {
            if (v2 === void 0) {
              if (bf2.__staleWhileFetching) {
                this.#valList[index] = bf2.__staleWhileFetching;
              } else {
                this.#delete(k, "fetch");
              }
            } else {
              if (options.status)
                options.status.fetchUpdated = true;
              this.set(k, v2, fetchOpts.options);
            }
          }
          return v2;
        }, "cb");
        const eb = /* @__PURE__ */ __name((er) => {
          if (options.status) {
            options.status.fetchRejected = true;
            options.status.fetchError = er;
          }
          return fetchFail(er);
        }, "eb");
        const fetchFail = /* @__PURE__ */ __name((er) => {
          const { aborted } = ac.signal;
          const allowStaleAborted = aborted && options.allowStaleOnFetchAbort;
          const allowStale = allowStaleAborted || options.allowStaleOnFetchRejection;
          const noDelete = allowStale || options.noDeleteOnFetchRejection;
          const bf2 = p;
          if (this.#valList[index] === p) {
            const del = !noDelete || bf2.__staleWhileFetching === void 0;
            if (del) {
              this.#delete(k, "fetch");
            } else if (!allowStaleAborted) {
              this.#valList[index] = bf2.__staleWhileFetching;
            }
          }
          if (allowStale) {
            if (options.status && bf2.__staleWhileFetching !== void 0) {
              options.status.returnedStale = true;
            }
            return bf2.__staleWhileFetching;
          } else if (bf2.__returned === bf2) {
            throw er;
          }
        }, "fetchFail");
        const pcall = /* @__PURE__ */ __name((res, rej) => {
          const fmp = this.#fetchMethod?.(k, v, fetchOpts);
          if (fmp && fmp instanceof Promise) {
            fmp.then((v2) => res(v2 === void 0 ? void 0 : v2), rej);
          }
          ac.signal.addEventListener("abort", () => {
            if (!options.ignoreFetchAbort || options.allowStaleOnFetchAbort) {
              res(void 0);
              if (options.allowStaleOnFetchAbort) {
                res = /* @__PURE__ */ __name((v2) => cb(v2, true), "res");
              }
            }
          });
        }, "pcall");
        if (options.status)
          options.status.fetchDispatched = true;
        const p = new Promise(pcall).then(cb, eb);
        const bf = Object.assign(p, {
          __abortController: ac,
          __staleWhileFetching: v,
          __returned: void 0
        });
        if (index === void 0) {
          this.set(k, bf, { ...fetchOpts.options, status: void 0 });
          index = this.#keyMap.get(k);
        } else {
          this.#valList[index] = bf;
        }
        return bf;
      }
      #isBackgroundFetch(p) {
        if (!this.#hasFetchMethod)
          return false;
        const b = p;
        return !!b && b instanceof Promise && b.hasOwnProperty("__staleWhileFetching") && b.__abortController instanceof AC;
      }
      async fetch(k, fetchOptions = {}) {
        const {
          // get options
          allowStale = this.allowStale,
          updateAgeOnGet = this.updateAgeOnGet,
          noDeleteOnStaleGet = this.noDeleteOnStaleGet,
          // set options
          ttl = this.ttl,
          noDisposeOnSet = this.noDisposeOnSet,
          size = 0,
          sizeCalculation = this.sizeCalculation,
          noUpdateTTL = this.noUpdateTTL,
          // fetch exclusive options
          noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,
          allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,
          ignoreFetchAbort = this.ignoreFetchAbort,
          allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,
          context,
          forceRefresh = false,
          status,
          signal
        } = fetchOptions;
        if (!this.#hasFetchMethod) {
          if (status)
            status.fetch = "get";
          return this.get(k, {
            allowStale,
            updateAgeOnGet,
            noDeleteOnStaleGet,
            status
          });
        }
        const options = {
          allowStale,
          updateAgeOnGet,
          noDeleteOnStaleGet,
          ttl,
          noDisposeOnSet,
          size,
          sizeCalculation,
          noUpdateTTL,
          noDeleteOnFetchRejection,
          allowStaleOnFetchRejection,
          allowStaleOnFetchAbort,
          ignoreFetchAbort,
          status,
          signal
        };
        let index = this.#keyMap.get(k);
        if (index === void 0) {
          if (status)
            status.fetch = "miss";
          const p = this.#backgroundFetch(k, index, options, context);
          return p.__returned = p;
        } else {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            const stale = allowStale && v.__staleWhileFetching !== void 0;
            if (status) {
              status.fetch = "inflight";
              if (stale)
                status.returnedStale = true;
            }
            return stale ? v.__staleWhileFetching : v.__returned = v;
          }
          const isStale = this.#isStale(index);
          if (!forceRefresh && !isStale) {
            if (status)
              status.fetch = "hit";
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            if (status)
              this.#statusTTL(status, index);
            return v;
          }
          const p = this.#backgroundFetch(k, index, options, context);
          const hasStale = p.__staleWhileFetching !== void 0;
          const staleVal = hasStale && allowStale;
          if (status) {
            status.fetch = isStale ? "stale" : "refresh";
            if (staleVal && isStale)
              status.returnedStale = true;
          }
          return staleVal ? p.__staleWhileFetching : p.__returned = p;
        }
      }
      async forceFetch(k, fetchOptions = {}) {
        const v = await this.fetch(k, fetchOptions);
        if (v === void 0)
          throw new Error("fetch() returned undefined");
        return v;
      }
      memo(k, memoOptions = {}) {
        const memoMethod = this.#memoMethod;
        if (!memoMethod) {
          throw new Error("no memoMethod provided to constructor");
        }
        const { context, forceRefresh, ...options } = memoOptions;
        const v = this.get(k, options);
        if (!forceRefresh && v !== void 0)
          return v;
        const vv = memoMethod(k, v, {
          options,
          context
        });
        this.set(k, vv, options);
        return vv;
      }
      /**
       * Return a value from the cache. Will update the recency of the cache
       * entry found.
       *
       * If the key is not found, get() will return `undefined`.
       */
      get(k, getOptions = {}) {
        const { allowStale = this.allowStale, updateAgeOnGet = this.updateAgeOnGet, noDeleteOnStaleGet = this.noDeleteOnStaleGet, status } = getOptions;
        const index = this.#keyMap.get(k);
        if (index !== void 0) {
          const value = this.#valList[index];
          const fetching = this.#isBackgroundFetch(value);
          if (status)
            this.#statusTTL(status, index);
          if (this.#isStale(index)) {
            if (status)
              status.get = "stale";
            if (!fetching) {
              if (!noDeleteOnStaleGet) {
                this.#delete(k, "expire");
              }
              if (status && allowStale)
                status.returnedStale = true;
              return allowStale ? value : void 0;
            } else {
              if (status && allowStale && value.__staleWhileFetching !== void 0) {
                status.returnedStale = true;
              }
              return allowStale ? value.__staleWhileFetching : void 0;
            }
          } else {
            if (status)
              status.get = "hit";
            if (fetching) {
              return value.__staleWhileFetching;
            }
            this.#moveToTail(index);
            if (updateAgeOnGet) {
              this.#updateItemAge(index);
            }
            return value;
          }
        } else if (status) {
          status.get = "miss";
        }
      }
      #connect(p, n) {
        this.#prev[n] = p;
        this.#next[p] = n;
      }
      #moveToTail(index) {
        if (index !== this.#tail) {
          if (index === this.#head) {
            this.#head = this.#next[index];
          } else {
            this.#connect(this.#prev[index], this.#next[index]);
          }
          this.#connect(this.#tail, index);
          this.#tail = index;
        }
      }
      /**
       * Deletes a key out of the cache.
       *
       * Returns true if the key was deleted, false otherwise.
       */
      delete(k) {
        return this.#delete(k, "delete");
      }
      #delete(k, reason) {
        let deleted = false;
        if (this.#size !== 0) {
          const index = this.#keyMap.get(k);
          if (index !== void 0) {
            deleted = true;
            if (this.#size === 1) {
              this.#clear(reason);
            } else {
              this.#removeItemSize(index);
              const v = this.#valList[index];
              if (this.#isBackgroundFetch(v)) {
                v.__abortController.abort(new Error("deleted"));
              } else if (this.#hasDispose || this.#hasDisposeAfter) {
                if (this.#hasDispose) {
                  this.#dispose?.(v, k, reason);
                }
                if (this.#hasDisposeAfter) {
                  this.#disposed?.push([v, k, reason]);
                }
              }
              this.#keyMap.delete(k);
              this.#keyList[index] = void 0;
              this.#valList[index] = void 0;
              if (index === this.#tail) {
                this.#tail = this.#prev[index];
              } else if (index === this.#head) {
                this.#head = this.#next[index];
              } else {
                const pi = this.#prev[index];
                this.#next[pi] = this.#next[index];
                const ni = this.#next[index];
                this.#prev[ni] = this.#prev[index];
              }
              this.#size--;
              this.#free.push(index);
            }
          }
        }
        if (this.#hasDisposeAfter && this.#disposed?.length) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
        return deleted;
      }
      /**
       * Clear the cache entirely, throwing away all values.
       */
      clear() {
        return this.#clear("delete");
      }
      #clear(reason) {
        for (const index of this.#rindexes({ allowStale: true })) {
          const v = this.#valList[index];
          if (this.#isBackgroundFetch(v)) {
            v.__abortController.abort(new Error("deleted"));
          } else {
            const k = this.#keyList[index];
            if (this.#hasDispose) {
              this.#dispose?.(v, k, reason);
            }
            if (this.#hasDisposeAfter) {
              this.#disposed?.push([v, k, reason]);
            }
          }
        }
        this.#keyMap.clear();
        this.#valList.fill(void 0);
        this.#keyList.fill(void 0);
        if (this.#ttls && this.#starts) {
          this.#ttls.fill(0);
          this.#starts.fill(0);
        }
        if (this.#sizes) {
          this.#sizes.fill(0);
        }
        this.#head = 0;
        this.#tail = 0;
        this.#free.length = 0;
        this.#calculatedSize = 0;
        this.#size = 0;
        if (this.#hasDisposeAfter && this.#disposed) {
          const dt = this.#disposed;
          let task;
          while (task = dt?.shift()) {
            this.#disposeAfter?.(...task);
          }
        }
      }
    };
    exports.LRUCache = LRUCache;
  }
});

// node_modules/hosted-git-info/lib/hosts.js
var require_hosts = __commonJS({
  "node_modules/hosted-git-info/lib/hosts.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var maybeJoin = /* @__PURE__ */ __name((...args) => args.every((arg) => arg) ? args.join("") : "", "maybeJoin");
    var maybeEncode = /* @__PURE__ */ __name((arg) => arg ? encodeURIComponent(arg) : "", "maybeEncode");
    var formatHashFragment = /* @__PURE__ */ __name((f) => f.toLowerCase().replace(/^\W+/g, "").replace(/(?<!\W)\W+$/, "").replace(/\//g, "").replace(/\W+/g, "-"), "formatHashFragment");
    var defaults = {
      sshtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `git@${domain}:${user}/${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `git+ssh://git@${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, editpath, path: path9 }) => `https://${domain}/${user}/${project}${maybeJoin("/", editpath, "/", maybeEncode(committish || "HEAD"), "/", path9)}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath, path: path9, fragment, hashformat }) => `https://${domain}/${user}/${project}/${treepath}/${maybeEncode(committish || "HEAD")}/${path9}${maybeJoin("#", hashformat(fragment || ""))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, blobpath, path: path9, fragment, hashformat }) => `https://${domain}/${user}/${project}/${blobpath}/${maybeEncode(committish || "HEAD")}/${path9}${maybeJoin("#", hashformat(fragment || ""))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain, user, project, treepath, committish }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish))}#readme`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, path: path9 }) => `https://${domain}/${user}/${project}/raw/${maybeEncode(committish || "HEAD")}/${path9}`, "filetemplate"),
      shortcuttemplate: /* @__PURE__ */ __name(({ type, user, project, committish }) => `${type}:${user}/${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
      pathtemplate: /* @__PURE__ */ __name(({ user, project, committish }) => `${user}/${project}${maybeJoin("#", committish)}`, "pathtemplate"),
      bugstemplate: /* @__PURE__ */ __name(({ domain, user, project }) => `https://${domain}/${user}/${project}/issues`, "bugstemplate"),
      hashformat: formatHashFragment
    };
    var hosts = {};
    hosts.github = {
      // First two are insecure and generally shouldn't be used any more, but
      // they are still supported.
      protocols: ["git:", "http:", "git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "github.com",
      treepath: "tree",
      blobpath: "blob",
      editpath: "edit",
      filetemplate: /* @__PURE__ */ __name(({ auth, user, project, committish, path: path9 }) => `https://${maybeJoin(auth, "@")}raw.githubusercontent.com/${user}/${project}/${maybeEncode(committish || "HEAD")}/${path9}`, "filetemplate"),
      gittemplate: /* @__PURE__ */ __name(({ auth, domain, user, project, committish }) => `git://${maybeJoin(auth, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://codeload.${domain}/${user}/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url) => {
        let [, user, project, type, committish] = url.pathname.split("/", 5);
        if (type && type !== "tree") {
          return;
        }
        if (!type) {
          committish = url.hash.slice(1);
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish };
      }, "extract")
    };
    hosts.bitbucket = {
      protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "bitbucket.org",
      treepath: "src",
      blobpath: "src",
      editpath: "?mode=edit",
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, treepath, path: path9, editpath }) => `https://${domain}/${user}/${project}${maybeJoin("/", treepath, "/", maybeEncode(committish || "HEAD"), "/", path9, editpath)}`, "edittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/get/${maybeEncode(committish || "HEAD")}.tar.gz`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url) => {
        let [, user, project, aux] = url.pathname.split("/", 4);
        if (["get"].includes(aux)) {
          return;
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url.hash.slice(1) };
      }, "extract")
    };
    hosts.gitlab = {
      protocols: ["git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "gitlab.com",
      treepath: "tree",
      blobpath: "tree",
      editpath: "-/edit",
      httpstemplate: /* @__PURE__ */ __name(({ auth, domain, user, project, committish }) => `git+https://${maybeJoin(auth, "@")}${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/repository/archive.tar.gz?ref=${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url) => {
        const path9 = url.pathname.slice(1);
        if (path9.includes("/-/") || path9.includes("/archive.tar.gz")) {
          return;
        }
        const segments = path9.split("/");
        let project = segments.pop();
        if (project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        const user = segments.join("/");
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url.hash.slice(1) };
      }, "extract")
    };
    hosts.gist = {
      protocols: ["git:", "git+ssh:", "git+https:", "ssh:", "https:"],
      domain: "gist.github.com",
      editpath: "edit",
      sshtemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git@${domain}:${project}.git${maybeJoin("#", committish)}`, "sshtemplate"),
      sshurltemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git+ssh://git@${domain}/${project}.git${maybeJoin("#", committish)}`, "sshurltemplate"),
      edittemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, editpath }) => `https://${domain}/${user}/${project}${maybeJoin("/", maybeEncode(committish))}/${editpath}`, "edittemplate"),
      browsetemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}`, "browsetemplate"),
      browsetreetemplate: /* @__PURE__ */ __name(({ domain, project, committish, path: path9, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path9))}`, "browsetreetemplate"),
      browseblobtemplate: /* @__PURE__ */ __name(({ domain, project, committish, path: path9, hashformat }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}${maybeJoin("#", hashformat(path9))}`, "browseblobtemplate"),
      docstemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `https://${domain}/${project}${maybeJoin("/", maybeEncode(committish))}`, "docstemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git+https://${domain}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      filetemplate: /* @__PURE__ */ __name(({ user, project, committish, path: path9 }) => `https://gist.githubusercontent.com/${user}/${project}/raw${maybeJoin("/", maybeEncode(committish))}/${path9}`, "filetemplate"),
      shortcuttemplate: /* @__PURE__ */ __name(({ type, project, committish }) => `${type}:${project}${maybeJoin("#", committish)}`, "shortcuttemplate"),
      pathtemplate: /* @__PURE__ */ __name(({ project, committish }) => `${project}${maybeJoin("#", committish)}`, "pathtemplate"),
      bugstemplate: /* @__PURE__ */ __name(({ domain, project }) => `https://${domain}/${project}`, "bugstemplate"),
      gittemplate: /* @__PURE__ */ __name(({ domain, project, committish }) => `git://${domain}/${project}.git${maybeJoin("#", committish)}`, "gittemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ project, committish }) => `https://codeload.github.com/gist/${project}/tar.gz/${maybeEncode(committish || "HEAD")}`, "tarballtemplate"),
      extract: /* @__PURE__ */ __name((url) => {
        let [, user, project, aux] = url.pathname.split("/", 4);
        if (aux === "raw") {
          return;
        }
        if (!project) {
          if (!user) {
            return;
          }
          project = user;
          user = null;
        }
        if (project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        return { user, project, committish: url.hash.slice(1) };
      }, "extract"),
      hashformat: /* @__PURE__ */ __name(function(fragment) {
        return fragment && "file-" + formatHashFragment(fragment);
      }, "hashformat")
    };
    hosts.sourcehut = {
      protocols: ["git+ssh:", "https:"],
      domain: "git.sr.ht",
      treepath: "tree",
      blobpath: "tree",
      filetemplate: /* @__PURE__ */ __name(({ domain, user, project, committish, path: path9 }) => `https://${domain}/${user}/${project}/blob/${maybeEncode(committish) || "HEAD"}/${path9}`, "filetemplate"),
      httpstemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}.git${maybeJoin("#", committish)}`, "httpstemplate"),
      tarballtemplate: /* @__PURE__ */ __name(({ domain, user, project, committish }) => `https://${domain}/${user}/${project}/archive/${maybeEncode(committish) || "HEAD"}.tar.gz`, "tarballtemplate"),
      bugstemplate: /* @__PURE__ */ __name(() => null, "bugstemplate"),
      extract: /* @__PURE__ */ __name((url) => {
        let [, user, project, aux] = url.pathname.split("/", 4);
        if (["archive"].includes(aux)) {
          return;
        }
        if (project && project.endsWith(".git")) {
          project = project.slice(0, -4);
        }
        if (!user || !project) {
          return;
        }
        return { user, project, committish: url.hash.slice(1) };
      }, "extract")
    };
    for (const [name, host] of Object.entries(hosts)) {
      hosts[name] = Object.assign({}, defaults, host);
    }
    module.exports = hosts;
  }
});

// node_modules/hosted-git-info/lib/parse-url.js
var require_parse_url = __commonJS({
  "node_modules/hosted-git-info/lib/parse-url.js"(exports, module) {
    init_esbuild_shims();
    var url = __require("url");
    var lastIndexOfBefore = /* @__PURE__ */ __name((str, char, beforeChar) => {
      const startPosition = str.indexOf(beforeChar);
      return str.lastIndexOf(char, startPosition > -1 ? startPosition : Infinity);
    }, "lastIndexOfBefore");
    var safeUrl = /* @__PURE__ */ __name((u) => {
      try {
        return new url.URL(u);
      } catch {
      }
    }, "safeUrl");
    var correctProtocol = /* @__PURE__ */ __name((arg, protocols) => {
      const firstColon = arg.indexOf(":");
      const proto = arg.slice(0, firstColon + 1);
      if (Object.prototype.hasOwnProperty.call(protocols, proto)) {
        return arg;
      }
      const firstAt = arg.indexOf("@");
      if (firstAt > -1) {
        if (firstAt > firstColon) {
          return `git+ssh://${arg}`;
        } else {
          return arg;
        }
      }
      const doubleSlash = arg.indexOf("//");
      if (doubleSlash === firstColon + 1) {
        return arg;
      }
      return `${arg.slice(0, firstColon + 1)}//${arg.slice(firstColon + 1)}`;
    }, "correctProtocol");
    var correctUrl = /* @__PURE__ */ __name((giturl) => {
      const firstAt = lastIndexOfBefore(giturl, "@", "#");
      const lastColonBeforeHash = lastIndexOfBefore(giturl, ":", "#");
      if (lastColonBeforeHash > firstAt) {
        giturl = giturl.slice(0, lastColonBeforeHash) + "/" + giturl.slice(lastColonBeforeHash + 1);
      }
      if (lastIndexOfBefore(giturl, ":", "#") === -1 && giturl.indexOf("//") === -1) {
        giturl = `git+ssh://${giturl}`;
      }
      return giturl;
    }, "correctUrl");
    module.exports = (giturl, protocols) => {
      const withProtocol = protocols ? correctProtocol(giturl, protocols) : giturl;
      return safeUrl(withProtocol) || safeUrl(correctUrl(withProtocol));
    };
  }
});

// node_modules/hosted-git-info/lib/from-url.js
var require_from_url = __commonJS({
  "node_modules/hosted-git-info/lib/from-url.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var parseUrl = require_parse_url();
    var isGitHubShorthand = /* @__PURE__ */ __name((arg) => {
      const firstHash = arg.indexOf("#");
      const firstSlash = arg.indexOf("/");
      const secondSlash = arg.indexOf("/", firstSlash + 1);
      const firstColon = arg.indexOf(":");
      const firstSpace = /\s/.exec(arg);
      const firstAt = arg.indexOf("@");
      const spaceOnlyAfterHash = !firstSpace || firstHash > -1 && firstSpace.index > firstHash;
      const atOnlyAfterHash = firstAt === -1 || firstHash > -1 && firstAt > firstHash;
      const colonOnlyAfterHash = firstColon === -1 || firstHash > -1 && firstColon > firstHash;
      const secondSlashOnlyAfterHash = secondSlash === -1 || firstHash > -1 && secondSlash > firstHash;
      const hasSlash = firstSlash > 0;
      const doesNotEndWithSlash = firstHash > -1 ? arg[firstHash - 1] !== "/" : !arg.endsWith("/");
      const doesNotStartWithDot = !arg.startsWith(".");
      return spaceOnlyAfterHash && hasSlash && doesNotEndWithSlash && doesNotStartWithDot && atOnlyAfterHash && colonOnlyAfterHash && secondSlashOnlyAfterHash;
    }, "isGitHubShorthand");
    module.exports = (giturl, opts, { gitHosts, protocols }) => {
      if (!giturl) {
        return;
      }
      const correctedUrl = isGitHubShorthand(giturl) ? `github:${giturl}` : giturl;
      const parsed = parseUrl(correctedUrl, protocols);
      if (!parsed) {
        return;
      }
      const gitHostShortcut = gitHosts.byShortcut[parsed.protocol];
      const gitHostDomain = gitHosts.byDomain[parsed.hostname.startsWith("www.") ? parsed.hostname.slice(4) : parsed.hostname];
      const gitHostName = gitHostShortcut || gitHostDomain;
      if (!gitHostName) {
        return;
      }
      const gitHostInfo = gitHosts[gitHostShortcut || gitHostDomain];
      let auth = null;
      if (protocols[parsed.protocol]?.auth && (parsed.username || parsed.password)) {
        auth = `${parsed.username}${parsed.password ? ":" + parsed.password : ""}`;
      }
      let committish = null;
      let user = null;
      let project = null;
      let defaultRepresentation = null;
      try {
        if (gitHostShortcut) {
          let pathname = parsed.pathname.startsWith("/") ? parsed.pathname.slice(1) : parsed.pathname;
          const firstAt = pathname.indexOf("@");
          if (firstAt > -1) {
            pathname = pathname.slice(firstAt + 1);
          }
          const lastSlash = pathname.lastIndexOf("/");
          if (lastSlash > -1) {
            user = decodeURIComponent(pathname.slice(0, lastSlash));
            if (!user) {
              user = null;
            }
            project = decodeURIComponent(pathname.slice(lastSlash + 1));
          } else {
            project = decodeURIComponent(pathname);
          }
          if (project.endsWith(".git")) {
            project = project.slice(0, -4);
          }
          if (parsed.hash) {
            committish = decodeURIComponent(parsed.hash.slice(1));
          }
          defaultRepresentation = "shortcut";
        } else {
          if (!gitHostInfo.protocols.includes(parsed.protocol)) {
            return;
          }
          const segments = gitHostInfo.extract(parsed);
          if (!segments) {
            return;
          }
          user = segments.user && decodeURIComponent(segments.user);
          project = decodeURIComponent(segments.project);
          committish = decodeURIComponent(segments.committish);
          defaultRepresentation = protocols[parsed.protocol]?.name || parsed.protocol.slice(0, -1);
        }
      } catch (err) {
        if (err instanceof URIError) {
          return;
        } else {
          throw err;
        }
      }
      return [gitHostName, user, auth, project, committish, defaultRepresentation, opts];
    };
  }
});

// node_modules/hosted-git-info/lib/index.js
var require_lib3 = __commonJS({
  "node_modules/hosted-git-info/lib/index.js"(exports, module) {
    "use strict";
    init_esbuild_shims();
    var { LRUCache } = require_commonjs();
    var hosts = require_hosts();
    var fromUrl = require_from_url();
    var parseUrl = require_parse_url();
    var cache = new LRUCache({ max: 1e3 });
    function unknownHostedUrl(url) {
      try {
        const {
          protocol,
          hostname,
          pathname
        } = new URL(url);
        if (!hostname) {
          return null;
        }
        const proto = /(?:git\+)http:$/.test(protocol) ? "http:" : "https:";
        const path9 = pathname.replace(/\.git$/, "");
        return `${proto}//${hostname}${path9}`;
      } catch {
        return null;
      }
    }
    __name(unknownHostedUrl, "unknownHostedUrl");
    var GitHost = class _GitHost {
      static {
        __name(this, "GitHost");
      }
      constructor(type, user, auth, project, committish, defaultRepresentation, opts = {}) {
        Object.assign(this, _GitHost.#gitHosts[type], {
          type,
          user,
          auth,
          project,
          committish,
          default: defaultRepresentation,
          opts
        });
      }
      static #gitHosts = { byShortcut: {}, byDomain: {} };
      static #protocols = {
        "git+ssh:": { name: "sshurl" },
        "ssh:": { name: "sshurl" },
        "git+https:": { name: "https", auth: true },
        "git:": { auth: true },
        "http:": { auth: true },
        "https:": { auth: true },
        "git+http:": { auth: true }
      };
      static addHost(name, host) {
        _GitHost.#gitHosts[name] = host;
        _GitHost.#gitHosts.byDomain[host.domain] = name;
        _GitHost.#gitHosts.byShortcut[`${name}:`] = name;
        _GitHost.#protocols[`${name}:`] = { name };
      }
      static fromUrl(giturl, opts) {
        if (typeof giturl !== "string") {
          return;
        }
        const key = giturl + JSON.stringify(opts || {});
        if (!cache.has(key)) {
          const hostArgs = fromUrl(giturl, opts, {
            gitHosts: _GitHost.#gitHosts,
            protocols: _GitHost.#protocols
          });
          cache.set(key, hostArgs ? new _GitHost(...hostArgs) : void 0);
        }
        return cache.get(key);
      }
      static fromManifest(manifest, opts = {}) {
        if (!manifest || typeof manifest !== "object") {
          return;
        }
        const r = manifest.repository;
        const rurl = r && (typeof r === "string" ? r : typeof r === "object" && typeof r.url === "string" ? r.url : null);
        if (!rurl) {
          throw new Error("no repository");
        }
        const info = rurl && _GitHost.fromUrl(rurl.replace(/^git\+/, ""), opts) || null;
        if (info) {
          return info;
        }
        const unk = unknownHostedUrl(rurl);
        return _GitHost.fromUrl(unk, opts) || unk;
      }
      static parseUrl(url) {
        return parseUrl(url);
      }
      #fill(template, opts) {
        if (typeof template !== "function") {
          return null;
        }
        const options = { ...this, ...this.opts, ...opts };
        if (!options.path) {
          options.path = "";
        }
        if (options.path.startsWith("/")) {
          options.path = options.path.slice(1);
        }
        if (options.noCommittish) {
          options.committish = null;
        }
        const result = template(options);
        return options.noGitPlus && result.startsWith("git+") ? result.slice(4) : result;
      }
      hash() {
        return this.committish ? `#${this.committish}` : "";
      }
      ssh(opts) {
        return this.#fill(this.sshtemplate, opts);
      }
      sshurl(opts) {
        return this.#fill(this.sshurltemplate, opts);
      }
      browse(path9, ...args) {
        if (typeof path9 !== "string") {
          return this.#fill(this.browsetemplate, path9);
        }
        if (typeof args[0] !== "string") {
          return this.#fill(this.browsetreetemplate, { ...args[0], path: path9 });
        }
        return this.#fill(this.browsetreetemplate, { ...args[1], fragment: args[0], path: path9 });
      }
      // If the path is known to be a file, then browseFile should be used. For some hosts
      // the url is the same as browse, but for others like GitHub a file can use both `/tree/`
      // and `/blob/` in the path. When using a default committish of `HEAD` then the `/tree/`
      // path will redirect to a specific commit. Using the `/blob/` path avoids this and
      // does not redirect to a different commit.
      browseFile(path9, ...args) {
        if (typeof args[0] !== "string") {
          return this.#fill(this.browseblobtemplate, { ...args[0], path: path9 });
        }
        return this.#fill(this.browseblobtemplate, { ...args[1], fragment: args[0], path: path9 });
      }
      docs(opts) {
        return this.#fill(this.docstemplate, opts);
      }
      bugs(opts) {
        return this.#fill(this.bugstemplate, opts);
      }
      https(opts) {
        return this.#fill(this.httpstemplate, opts);
      }
      git(opts) {
        return this.#fill(this.gittemplate, opts);
      }
      shortcut(opts) {
        return this.#fill(this.shortcuttemplate, opts);
      }
      path(opts) {
        return this.#fill(this.pathtemplate, opts);
      }
      tarball(opts) {
        return this.#fill(this.tarballtemplate, { ...opts, noCommittish: false });
      }
      file(path9, opts) {
        return this.#fill(this.filetemplate, { ...opts, path: path9 });
      }
      edit(path9, opts) {
        return this.#fill(this.edittemplate, { ...opts, path: path9 });
      }
      getDefaultRepresentation() {
        return this.default;
      }
      toString(opts) {
        if (this.default && typeof this[this.default] === "function") {
          return this[this.default](opts);
        }
        return this.sshurl(opts);
      }
    };
    for (const [name, host] of Object.entries(hosts)) {
      GitHost.addHost(name, host);
    }
    module.exports = GitHost;
  }
});

// node_modules/normalize-package-data/lib/extract_description.js
var require_extract_description = __commonJS({
  "node_modules/normalize-package-data/lib/extract_description.js"(exports, module) {
    init_esbuild_shims();
    module.exports = extractDescription;
    function extractDescription(d) {
      if (!d) {
        return;
      }
      if (d === "ERROR: No README data found!") {
        return;
      }
      d = d.trim().split("\n");
      let s = 0;
      while (d[s] && d[s].trim().match(/^(#|$)/)) {
        s++;
      }
      const l = d.length;
      let e = s + 1;
      while (e < l && d[e].trim()) {
        e++;
      }
      return d.slice(s, e).join(" ").trim();
    }
    __name(extractDescription, "extractDescription");
  }
});

// node_modules/normalize-package-data/lib/typos.json
var require_typos = __commonJS({
  "node_modules/normalize-package-data/lib/typos.json"(exports, module) {
    module.exports = {
      topLevel: {
        dependancies: "dependencies",
        dependecies: "dependencies",
        depdenencies: "dependencies",
        devEependencies: "devDependencies",
        depends: "dependencies",
        "dev-dependencies": "devDependencies",
        devDependences: "devDependencies",
        devDepenencies: "devDependencies",
        devdependencies: "devDependencies",
        repostitory: "repository",
        repo: "repository",
        prefereGlobal: "preferGlobal",
        hompage: "homepage",
        hampage: "homepage",
        autohr: "author",
        autor: "author",
        contributers: "contributors",
        publicationConfig: "publishConfig",
        script: "scripts"
      },
      bugs: { web: "url", name: "url" },
      script: { server: "start", tests: "test" }
    };
  }
});

// node_modules/normalize-package-data/lib/fixer.js
var require_fixer = __commonJS({
  "node_modules/normalize-package-data/lib/fixer.js"(exports, module) {
    init_esbuild_shims();
    var { URL: URL2 } = __require("node:url");
    var isValidSemver = require_valid();
    var cleanSemver = require_clean();
    var validateLicense = require_validate_npm_package_license();
    var hostedGitInfo = require_lib3();
    var { isBuiltin } = __require("node:module");
    var depTypes = ["dependencies", "devDependencies", "optionalDependencies"];
    var extractDescription = require_extract_description();
    var typos = require_typos();
    var isEmail = /* @__PURE__ */ __name((str) => str.includes("@") && str.indexOf("@") < str.lastIndexOf("."), "isEmail");
    module.exports = {
      // default warning function
      warn: /* @__PURE__ */ __name(function() {
      }, "warn"),
      fixRepositoryField: /* @__PURE__ */ __name(function(data) {
        if (data.repositories) {
          this.warn("repositories");
          data.repository = data.repositories[0];
        }
        if (!data.repository) {
          return this.warn("missingRepository");
        }
        if (typeof data.repository === "string") {
          data.repository = {
            type: "git",
            url: data.repository
          };
        }
        var r = data.repository.url || "";
        if (r) {
          var hosted = hostedGitInfo.fromUrl(r);
          if (hosted) {
            r = data.repository.url = hosted.getDefaultRepresentation() === "shortcut" ? hosted.https() : hosted.toString();
          }
        }
        if (r.match(/github.com\/[^/]+\/[^/]+\.git\.git$/)) {
          this.warn("brokenGitUrl", r);
        }
      }, "fixRepositoryField"),
      fixTypos: /* @__PURE__ */ __name(function(data) {
        Object.keys(typos.topLevel).forEach(function(d) {
          if (Object.prototype.hasOwnProperty.call(data, d)) {
            this.warn("typo", d, typos.topLevel[d]);
          }
        }, this);
      }, "fixTypos"),
      fixScriptsField: /* @__PURE__ */ __name(function(data) {
        if (!data.scripts) {
          return;
        }
        if (typeof data.scripts !== "object") {
          this.warn("nonObjectScripts");
          delete data.scripts;
          return;
        }
        Object.keys(data.scripts).forEach(function(k) {
          if (typeof data.scripts[k] !== "string") {
            this.warn("nonStringScript");
            delete data.scripts[k];
          } else if (typos.script[k] && !data.scripts[typos.script[k]]) {
            this.warn("typo", k, typos.script[k], "scripts");
          }
        }, this);
      }, "fixScriptsField"),
      fixFilesField: /* @__PURE__ */ __name(function(data) {
        var files = data.files;
        if (files && !Array.isArray(files)) {
          this.warn("nonArrayFiles");
          delete data.files;
        } else if (data.files) {
          data.files = data.files.filter(function(file) {
            if (!file || typeof file !== "string") {
              this.warn("invalidFilename", file);
              return false;
            } else {
              return true;
            }
          }, this);
        }
      }, "fixFilesField"),
      fixBinField: /* @__PURE__ */ __name(function(data) {
        if (!data.bin) {
          return;
        }
        if (typeof data.bin === "string") {
          var b = {};
          var match;
          if (match = data.name.match(/^@[^/]+[/](.*)$/)) {
            b[match[1]] = data.bin;
          } else {
            b[data.name] = data.bin;
          }
          data.bin = b;
        }
      }, "fixBinField"),
      fixManField: /* @__PURE__ */ __name(function(data) {
        if (!data.man) {
          return;
        }
        if (typeof data.man === "string") {
          data.man = [data.man];
        }
      }, "fixManField"),
      fixBundleDependenciesField: /* @__PURE__ */ __name(function(data) {
        var bdd = "bundledDependencies";
        var bd = "bundleDependencies";
        if (data[bdd] && !data[bd]) {
          data[bd] = data[bdd];
          delete data[bdd];
        }
        if (data[bd] && !Array.isArray(data[bd])) {
          this.warn("nonArrayBundleDependencies");
          delete data[bd];
        } else if (data[bd]) {
          data[bd] = data[bd].filter(function(filtered) {
            if (!filtered || typeof filtered !== "string") {
              this.warn("nonStringBundleDependency", filtered);
              return false;
            } else {
              if (!data.dependencies) {
                data.dependencies = {};
              }
              if (!Object.prototype.hasOwnProperty.call(data.dependencies, filtered)) {
                this.warn("nonDependencyBundleDependency", filtered);
                data.dependencies[filtered] = "*";
              }
              return true;
            }
          }, this);
        }
      }, "fixBundleDependenciesField"),
      fixDependencies: /* @__PURE__ */ __name(function(data) {
        objectifyDeps(data, this.warn);
        addOptionalDepsToDeps(data, this.warn);
        this.fixBundleDependenciesField(data);
        ["dependencies", "devDependencies"].forEach(function(deps) {
          if (!(deps in data)) {
            return;
          }
          if (!data[deps] || typeof data[deps] !== "object") {
            this.warn("nonObjectDependencies", deps);
            delete data[deps];
            return;
          }
          Object.keys(data[deps]).forEach(function(d) {
            var r = data[deps][d];
            if (typeof r !== "string") {
              this.warn("nonStringDependency", d, JSON.stringify(r));
              delete data[deps][d];
            }
            var hosted = hostedGitInfo.fromUrl(data[deps][d]);
            if (hosted) {
              data[deps][d] = hosted.toString();
            }
          }, this);
        }, this);
      }, "fixDependencies"),
      fixModulesField: /* @__PURE__ */ __name(function(data) {
        if (data.modules) {
          this.warn("deprecatedModules");
          delete data.modules;
        }
      }, "fixModulesField"),
      fixKeywordsField: /* @__PURE__ */ __name(function(data) {
        if (typeof data.keywords === "string") {
          data.keywords = data.keywords.split(/,\s+/);
        }
        if (data.keywords && !Array.isArray(data.keywords)) {
          delete data.keywords;
          this.warn("nonArrayKeywords");
        } else if (data.keywords) {
          data.keywords = data.keywords.filter(function(kw) {
            if (typeof kw !== "string" || !kw) {
              this.warn("nonStringKeyword");
              return false;
            } else {
              return true;
            }
          }, this);
        }
      }, "fixKeywordsField"),
      fixVersionField: /* @__PURE__ */ __name(function(data, strict) {
        var loose = !strict;
        if (!data.version) {
          data.version = "";
          return true;
        }
        if (!isValidSemver(data.version, loose)) {
          throw new Error('Invalid version: "' + data.version + '"');
        }
        data.version = cleanSemver(data.version, loose);
        return true;
      }, "fixVersionField"),
      fixPeople: /* @__PURE__ */ __name(function(data) {
        modifyPeople(data, unParsePerson);
        modifyPeople(data, parsePerson);
      }, "fixPeople"),
      fixNameField: /* @__PURE__ */ __name(function(data, options) {
        if (typeof options === "boolean") {
          options = { strict: options };
        } else if (typeof options === "undefined") {
          options = {};
        }
        var strict = options.strict;
        if (!data.name && !strict) {
          data.name = "";
          return;
        }
        if (typeof data.name !== "string") {
          throw new Error("name field must be a string.");
        }
        if (!strict) {
          data.name = data.name.trim();
        }
        ensureValidName(data.name, strict, options.allowLegacyCase);
        if (isBuiltin(data.name)) {
          this.warn("conflictingName", data.name);
        }
      }, "fixNameField"),
      fixDescriptionField: /* @__PURE__ */ __name(function(data) {
        if (data.description && typeof data.description !== "string") {
          this.warn("nonStringDescription");
          delete data.description;
        }
        if (data.readme && !data.description) {
          data.description = extractDescription(data.readme);
        }
        if (data.description === void 0) {
          delete data.description;
        }
        if (!data.description) {
          this.warn("missingDescription");
        }
      }, "fixDescriptionField"),
      fixReadmeField: /* @__PURE__ */ __name(function(data) {
        if (!data.readme) {
          this.warn("missingReadme");
          data.readme = "ERROR: No README data found!";
        }
      }, "fixReadmeField"),
      fixBugsField: /* @__PURE__ */ __name(function(data) {
        if (!data.bugs && data.repository && data.repository.url) {
          var hosted = hostedGitInfo.fromUrl(data.repository.url);
          if (hosted && hosted.bugs()) {
            data.bugs = { url: hosted.bugs() };
          }
        } else if (data.bugs) {
          if (typeof data.bugs === "string") {
            if (isEmail(data.bugs)) {
              data.bugs = { email: data.bugs };
            } else if (URL2.canParse(data.bugs)) {
              data.bugs = { url: data.bugs };
            } else {
              this.warn("nonEmailUrlBugsString");
            }
          } else {
            bugsTypos(data.bugs, this.warn);
            var oldBugs = data.bugs;
            data.bugs = {};
            if (oldBugs.url) {
              if (URL2.canParse(oldBugs.url)) {
                data.bugs.url = oldBugs.url;
              } else {
                this.warn("nonUrlBugsUrlField");
              }
            }
            if (oldBugs.email) {
              if (typeof oldBugs.email === "string" && isEmail(oldBugs.email)) {
                data.bugs.email = oldBugs.email;
              } else {
                this.warn("nonEmailBugsEmailField");
              }
            }
          }
          if (!data.bugs.email && !data.bugs.url) {
            delete data.bugs;
            this.warn("emptyNormalizedBugs");
          }
        }
      }, "fixBugsField"),
      fixHomepageField: /* @__PURE__ */ __name(function(data) {
        if (!data.homepage && data.repository && data.repository.url) {
          var hosted = hostedGitInfo.fromUrl(data.repository.url);
          if (hosted && hosted.docs()) {
            data.homepage = hosted.docs();
          }
        }
        if (!data.homepage) {
          return;
        }
        if (typeof data.homepage !== "string") {
          this.warn("nonUrlHomepage");
          return delete data.homepage;
        }
        if (!URL2.canParse(data.homepage)) {
          data.homepage = "http://" + data.homepage;
        }
      }, "fixHomepageField"),
      fixLicenseField: /* @__PURE__ */ __name(function(data) {
        const license = data.license || data.licence;
        if (!license) {
          return this.warn("missingLicense");
        }
        if (typeof license !== "string" || license.length < 1 || license.trim() === "") {
          return this.warn("invalidLicense");
        }
        if (!validateLicense(license).validForNewPackages) {
          return this.warn("invalidLicense");
        }
      }, "fixLicenseField")
    };
    function isValidScopedPackageName(spec) {
      if (spec.charAt(0) !== "@") {
        return false;
      }
      var rest = spec.slice(1).split("/");
      if (rest.length !== 2) {
        return false;
      }
      return rest[0] && rest[1] && rest[0] === encodeURIComponent(rest[0]) && rest[1] === encodeURIComponent(rest[1]);
    }
    __name(isValidScopedPackageName, "isValidScopedPackageName");
    function isCorrectlyEncodedName(spec) {
      return !spec.match(/[/@\s+%:]/) && spec === encodeURIComponent(spec);
    }
    __name(isCorrectlyEncodedName, "isCorrectlyEncodedName");
    function ensureValidName(name, strict, allowLegacyCase) {
      if (name.charAt(0) === "." || !(isValidScopedPackageName(name) || isCorrectlyEncodedName(name)) || strict && !allowLegacyCase && name !== name.toLowerCase() || name.toLowerCase() === "node_modules" || name.toLowerCase() === "favicon.ico") {
        throw new Error("Invalid name: " + JSON.stringify(name));
      }
    }
    __name(ensureValidName, "ensureValidName");
    function modifyPeople(data, fn) {
      if (data.author) {
        data.author = fn(data.author);
      }
      ["maintainers", "contributors"].forEach(function(set) {
        if (!Array.isArray(data[set])) {
          return;
        }
        data[set] = data[set].map(fn);
      });
      return data;
    }
    __name(modifyPeople, "modifyPeople");
    function unParsePerson(person) {
      if (typeof person === "string") {
        return person;
      }
      var name = person.name || "";
      var u = person.url || person.web;
      var wrappedUrl = u ? " (" + u + ")" : "";
      var e = person.email || person.mail;
      var wrappedEmail = e ? " <" + e + ">" : "";
      return name + wrappedEmail + wrappedUrl;
    }
    __name(unParsePerson, "unParsePerson");
    function parsePerson(person) {
      if (typeof person !== "string") {
        return person;
      }
      var matchedName = person.match(/^([^(<]+)/);
      var matchedUrl = person.match(/\(([^()]+)\)/);
      var matchedEmail = person.match(/<([^<>]+)>/);
      var obj = {};
      if (matchedName && matchedName[0].trim()) {
        obj.name = matchedName[0].trim();
      }
      if (matchedEmail) {
        obj.email = matchedEmail[1];
      }
      if (matchedUrl) {
        obj.url = matchedUrl[1];
      }
      return obj;
    }
    __name(parsePerson, "parsePerson");
    function addOptionalDepsToDeps(data) {
      var o = data.optionalDependencies;
      if (!o) {
        return;
      }
      var d = data.dependencies || {};
      Object.keys(o).forEach(function(k) {
        d[k] = o[k];
      });
      data.dependencies = d;
    }
    __name(addOptionalDepsToDeps, "addOptionalDepsToDeps");
    function depObjectify(deps, type, warn) {
      if (!deps) {
        return {};
      }
      if (typeof deps === "string") {
        deps = deps.trim().split(/[\n\r\s\t ,]+/);
      }
      if (!Array.isArray(deps)) {
        return deps;
      }
      warn("deprecatedArrayDependencies", type);
      var o = {};
      deps.filter(function(d) {
        return typeof d === "string";
      }).forEach(function(d) {
        d = d.trim().split(/(:?[@\s><=])/);
        var dn = d.shift();
        var dv = d.join("");
        dv = dv.trim();
        dv = dv.replace(/^@/, "");
        o[dn] = dv;
      });
      return o;
    }
    __name(depObjectify, "depObjectify");
    function objectifyDeps(data, warn) {
      depTypes.forEach(function(type) {
        if (!data[type]) {
          return;
        }
        data[type] = depObjectify(data[type], type, warn);
      });
    }
    __name(objectifyDeps, "objectifyDeps");
    function bugsTypos(bugs, warn) {
      if (!bugs) {
        return;
      }
      Object.keys(bugs).forEach(function(k) {
        if (typos.bugs[k]) {
          warn("typo", k, typos.bugs[k], "bugs");
          bugs[typos.bugs[k]] = bugs[k];
          delete bugs[k];
        }
      });
    }
    __name(bugsTypos, "bugsTypos");
  }
});

// node_modules/normalize-package-data/lib/warning_messages.json
var require_warning_messages = __commonJS({
  "node_modules/normalize-package-data/lib/warning_messages.json"(exports, module) {
    module.exports = {
      repositories: "'repositories' (plural) Not supported. Please pick one as the 'repository' field",
      missingRepository: "No repository field.",
      brokenGitUrl: "Probably broken git url: %s",
      nonObjectScripts: "scripts must be an object",
      nonStringScript: "script values must be string commands",
      nonArrayFiles: "Invalid 'files' member",
      invalidFilename: "Invalid filename in 'files' list: %s",
      nonArrayBundleDependencies: "Invalid 'bundleDependencies' list. Must be array of package names",
      nonStringBundleDependency: "Invalid bundleDependencies member: %s",
      nonDependencyBundleDependency: "Non-dependency in bundleDependencies: %s",
      nonObjectDependencies: "%s field must be an object",
      nonStringDependency: "Invalid dependency: %s %s",
      deprecatedArrayDependencies: "specifying %s as array is deprecated",
      deprecatedModules: "modules field is deprecated",
      nonArrayKeywords: "keywords should be an array of strings",
      nonStringKeyword: "keywords should be an array of strings",
      conflictingName: "%s is also the name of a node core module.",
      nonStringDescription: "'description' field should be a string",
      missingDescription: "No description",
      missingReadme: "No README data",
      missingLicense: "No license field.",
      nonEmailUrlBugsString: "Bug string field must be url, email, or {email,url}",
      nonUrlBugsUrlField: "bugs.url field must be a string url. Deleted.",
      nonEmailBugsEmailField: "bugs.email field must be a string email. Deleted.",
      emptyNormalizedBugs: "Normalized value of bugs field is an empty object. Deleted.",
      nonUrlHomepage: "homepage field must be a string url. Deleted.",
      invalidLicense: "license should be a valid SPDX license expression",
      typo: "%s should probably be %s."
    };
  }
});

// node_modules/normalize-package-data/lib/make_warning.js
var require_make_warning = __commonJS({
  "node_modules/normalize-package-data/lib/make_warning.js"(exports, module) {
    init_esbuild_shims();
    var util = __require("util");
    var messages = require_warning_messages();
    module.exports = function() {
      var args = Array.prototype.slice.call(arguments, 0);
      var warningName = args.shift();
      if (warningName === "typo") {
        return makeTypoWarning.apply(null, args);
      } else {
        var msgTemplate = messages[warningName] ? messages[warningName] : warningName + ": '%s'";
        args.unshift(msgTemplate);
        return util.format.apply(null, args);
      }
    };
    function makeTypoWarning(providedName, probableName, field) {
      if (field) {
        providedName = field + "['" + providedName + "']";
        probableName = field + "['" + probableName + "']";
      }
      return util.format(messages.typo, providedName, probableName);
    }
    __name(makeTypoWarning, "makeTypoWarning");
  }
});

// node_modules/normalize-package-data/lib/normalize.js
var require_normalize = __commonJS({
  "node_modules/normalize-package-data/lib/normalize.js"(exports, module) {
    init_esbuild_shims();
    module.exports = normalize3;
    var fixer = require_fixer();
    normalize3.fixer = fixer;
    var makeWarning = require_make_warning();
    var fieldsToFix = [
      "name",
      "version",
      "description",
      "repository",
      "modules",
      "scripts",
      "files",
      "bin",
      "man",
      "bugs",
      "keywords",
      "readme",
      "homepage",
      "license"
    ];
    var otherThingsToFix = ["dependencies", "people", "typos"];
    var thingsToFix = fieldsToFix.map(function(fieldName) {
      return ucFirst(fieldName) + "Field";
    });
    thingsToFix = thingsToFix.concat(otherThingsToFix);
    function normalize3(data, warn, strict) {
      if (warn === true) {
        warn = null;
        strict = true;
      }
      if (!strict) {
        strict = false;
      }
      if (!warn || data.private) {
        warn = /* @__PURE__ */ __name(function() {
        }, "warn");
      }
      if (data.scripts && data.scripts.install === "node-gyp rebuild" && !data.scripts.preinstall) {
        data.gypfile = true;
      }
      fixer.warn = function() {
        warn(makeWarning.apply(null, arguments));
      };
      thingsToFix.forEach(function(thingName) {
        fixer["fix" + ucFirst(thingName)](data, strict);
      });
      data._id = data.name + "@" + data.version;
    }
    __name(normalize3, "normalize");
    function ucFirst(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    __name(ucFirst, "ucFirst");
  }
});

// packages/acp-bridge/src/eventBus.ts
init_esbuild_shims();
var EVENT_SCHEMA_VERSION = 1;
var DEFAULT_MAX_QUEUED = 256;
var DEFAULT_RING_SIZE = 8e3;
var WARN_THRESHOLD_RATIO = 0.75;
var WARN_RESET_RATIO = 0.375;
var DEFAULT_MAX_SUBSCRIBERS = 64;
function getServerTimestamp(meta) {
  const existing = meta?.["serverTimestamp"];
  return typeof existing === "number" && Number.isFinite(existing) ? existing : Date.now();
}
__name(getServerTimestamp, "getServerTimestamp");
var SubscriberLimitExceededError = class extends Error {
  static {
    __name(this, "SubscriberLimitExceededError");
  }
  limit;
  constructor(limit) {
    super(`EventBus subscriber limit reached (${limit})`);
    this.name = "SubscriberLimitExceededError";
    this.limit = limit;
  }
};
var EventBus = class {
  constructor(ringSize = DEFAULT_RING_SIZE, maxSubscribers = DEFAULT_MAX_SUBSCRIBERS, compactionEngine) {
    this.ringSize = ringSize;
    this.maxSubscribers = maxSubscribers;
    this.compactionEngine = compactionEngine;
  }
  static {
    __name(this, "EventBus");
  }
  nextId = 1;
  ring = [];
  subs = /* @__PURE__ */ new Set();
  closed = false;
  snapshotReplay() {
    return this.compactionEngine?.snapshot();
  }
  /** Most recent id ever assigned by `publish`. 0 if no events published. */
  get lastEventId() {
    return this.nextId - 1;
  }
  /** Snapshot of the live subscriber count. */
  get subscriberCount() {
    return this.subs.size;
  }
  /**
   * Publish an event to the bus. Returns the constructed `BridgeEvent`
   * (with `id` + `v` assigned) on success, or `undefined` when the
   * bus is closed.
   *
   * **Never throws** (never-throws contract). Closing the bus mid-publish
   * is the only abnormal path and is handled as a return-undefined
   * no-op; subscriber-enqueue failures are caught internally and
   * translated to per-subscriber eviction. Call sites can rely on
   * this — the historical `try { publish(...) } catch {}` blocks in
   * `httpAcpBridge.ts` are defense-in-depth, not load-bearing, and
   * may be removed in a future cleanup pass without changing
   * behavior. Don't add new try/catch wrappers around `publish()`.
   */
  publish(input) {
    if (this.closed) return void 0;
    const existingMeta = input._meta;
    const event = {
      id: this.nextId++,
      v: EVENT_SCHEMA_VERSION,
      ...input,
      _meta: {
        ...existingMeta ?? {},
        serverTimestamp: getServerTimestamp(existingMeta)
      }
    };
    this.ring.push(event);
    try {
      this.compactionEngine?.ingest(event);
    } catch {
    }
    if (this.ring.length > this.ringSize) this.ring.shift();
    for (const sub of Array.from(this.subs)) {
      if (sub.evicted) continue;
      if (!sub.queue.push(event)) {
        sub.evicted = true;
        const evictionFrame = {
          v: EVENT_SCHEMA_VERSION,
          type: "client_evicted",
          data: { reason: "queue_overflow", droppedAfter: event.id }
        };
        sub.queue.forcePush(evictionFrame);
        sub.queue.close();
        sub.dispose();
        continue;
      }
      const liveSize = sub.queue.size;
      if (!sub.warned && liveSize >= sub.warnThreshold) {
        sub.warned = true;
        const warningFrame = {
          v: EVENT_SCHEMA_VERSION,
          type: "slow_client_warning",
          data: {
            queueSize: liveSize,
            maxQueued: sub.maxQueued,
            // `event.id` is always defined here — the just-published
            // `event` is constructed at the top of `publish()` with
            // `id: this.nextId++`. No `??` fallback needed.
            lastEventId: event.id
          }
        };
        sub.queue.forcePush(warningFrame);
      } else if (sub.warned && liveSize <= sub.warnResetThreshold) {
        sub.warned = false;
      }
    }
    return event;
  }
  /**
   * Note: registration is synchronous — by the time `subscribe()` returns,
   * the subscriber is already attached and will receive any subsequent
   * `publish()` even if the consumer hasn't started iterating yet. (A
   * generator-style implementation would defer registration to the first
   * `next()` call, which races with publishes that happen before the
   * consumer's first await.)
   *
   * The returned iterator is NOT safe to drive from concurrent callers —
   * two simultaneous `.next()` calls would race for the same event from
   * the underlying queue. Daemon usage is sequential (`for await ... of`
   * inside the SSE route), so this is safe in production. Callers that
   * fan an iterator out to multiple consumers must serialize themselves.
   */
  subscribe(opts = {}) {
    if (this.closed) {
      return emptyAsyncIterable();
    }
    if (this.subs.size >= this.maxSubscribers) {
      throw new SubscriberLimitExceededError(this.maxSubscribers);
    }
    const maxQueued = opts.maxQueued ?? DEFAULT_MAX_QUEUED;
    const queue = new BoundedAsyncQueue(maxQueued);
    const sub = {
      queue,
      evicted: false,
      maxQueued,
      warnThreshold: WARN_THRESHOLD_RATIO * maxQueued,
      warnResetThreshold: WARN_RESET_RATIO * maxQueued,
      warned: false,
      dispose: /* @__PURE__ */ __name(() => {
      }, "dispose")
    };
    this.subs.add(sub);
    if (opts.lastEventId !== void 0) {
      const epochReset = opts.lastEventId >= this.nextId;
      if (epochReset) {
        queue.forcePush({
          v: EVENT_SCHEMA_VERSION,
          type: "state_resync_required",
          data: {
            reason: "epoch_reset",
            lastDeliveredId: opts.lastEventId,
            // Ring is typically empty right after a restart; fall back to
            // `nextId` (the first id this epoch will assign) so the field
            // stays meaningful ("fresh sequence starts here").
            earliestAvailableId: this.ring[0]?.id ?? this.nextId
          }
        });
      } else {
        const earliestInRing = this.ring[0]?.id;
        if (earliestInRing !== void 0 && earliestInRing > opts.lastEventId + 1) {
          queue.forcePush({
            v: EVENT_SCHEMA_VERSION,
            type: "state_resync_required",
            data: {
              reason: "ring_evicted",
              lastDeliveredId: opts.lastEventId,
              earliestAvailableId: earliestInRing
            }
          });
        }
      }
      const replayFrom = epochReset ? 0 : opts.lastEventId;
      let replayedCount = 0;
      let lastReplayedId;
      for (const e of this.ring) {
        if (e.id !== void 0 && e.id > replayFrom) {
          queue.forcePush(e);
          replayedCount += 1;
          lastReplayedId = e.id;
        }
      }
      queue.forcePush({
        v: EVENT_SCHEMA_VERSION,
        type: "replay_complete",
        data: {
          // Note: `lastReplayedEventId`
          // is the canonical wire name — the old `lastEventId` collided
          // semantically with the SSE protocol's `Last-Event-ID` (envelope
          // `id`) in raw daemon traces. Emit both: `lastReplayedEventId`
          // for current SDKs and `lastEventId` as a deprecated alias so
          // pre-rename consumers keep working (additive, non-breaking).
          ...lastReplayedId !== void 0 ? {
            lastReplayedEventId: lastReplayedId,
            lastEventId: lastReplayedId
          } : {},
          replayedCount
        }
      });
    }
    let disposed = false;
    const dispose = /* @__PURE__ */ __name(() => {
      if (disposed) return;
      disposed = true;
      this.subs.delete(sub);
      opts.signal?.removeEventListener("abort", onAbort);
    }, "dispose");
    sub.dispose = dispose;
    const onAbort = /* @__PURE__ */ __name(() => {
      queue.close({ drain: false });
      dispose();
    }, "onAbort");
    if (opts.signal) {
      if (opts.signal.aborted) {
        onAbort();
      } else {
        opts.signal.addEventListener("abort", onAbort, { once: true });
      }
    }
    return {
      [Symbol.asyncIterator]: () => ({
        async next() {
          const r = await queue.next();
          if (r.done) dispose();
          return r;
        },
        async return() {
          queue.close();
          dispose();
          return { value: void 0, done: true };
        }
      })
    };
  }
  /** Close all live subscribers and prevent further `publish`/`subscribe`. */
  close() {
    if (this.closed) return;
    this.closed = true;
    for (const sub of this.subs) sub.queue.close();
    this.subs.clear();
    this.compactionEngine?.close();
  }
};
function emptyAsyncIterable() {
  return {
    [Symbol.asyncIterator]: () => ({
      async next() {
        return { value: void 0, done: true };
      }
    })
  };
}
__name(emptyAsyncIterable, "emptyAsyncIterable");
var BoundedAsyncQueue = class {
  constructor(maxSize) {
    this.maxSize = maxSize;
  }
  static {
    __name(this, "BoundedAsyncQueue");
  }
  buf = [];
  resolvers = [];
  closed = false;
  /**
   * O(1) snapshot of how many LIVE (non-forced) entries are in `buf`.
   * Maintained directly by `push()`/`next()`: any time a forced entry
   * is added or removed `liveCount` is untouched; any time a live entry
   * is added or removed `liveCount` moves with it. Replaces the
   * position-dependent `forcedInBuf` heuristic — `liveCount` is correct
   * no matter where in the queue the forced entries are.
   */
  liveCount = 0;
  /**
   * Number of LIVE (non-force-pushed) items currently waiting in the
   * buffer. Backpressure decisions in `EventBus.publish()` (the
   * `slow_client_warning` threshold) read this value.
   */
  get size() {
    return this.liveCount;
  }
  /** Returns true if accepted, false if dropped due to overflow. */
  push(value) {
    if (this.closed) return false;
    const r = this.resolvers.shift();
    if (r) {
      r({ value, done: false });
      return true;
    }
    if (this.liveCount >= this.maxSize) return false;
    this.buf.push({ value, forced: false });
    this.liveCount += 1;
    return true;
  }
  /** Bypasses the size cap. Used for replay frames, eviction terminal,
   * and slow-client warnings. */
  forcePush(value) {
    if (this.closed) return;
    const r = this.resolvers.shift();
    if (r) {
      r({ value, done: false });
      return;
    }
    this.buf.push({ value, forced: true });
  }
  /**
   * Mark the queue closed. By default `next()` continues to drain
   * any items already in `buf` before returning `done: true` —
   * that's what the eviction path relies on (the synthetic
   * `client_evicted` frame is force-pushed THEN close is called,
   * and we want the consumer to see the terminal frame before the
   * iterator unwinds).
   *
   * Pass `{ drain: false }` to drop buffered items immediately
   * (the AbortSignal-driven unsubscribe path uses this — the
   * subscribe docstring says abort should close the iterator
   * promptly, but draining hundreds of queued events first
   * contradicts that and adds post-abort work to the SSE route).
   */
  close(opts = {}) {
    if (this.closed) return;
    this.closed = true;
    if (opts.drain === false) {
      this.buf.length = 0;
      this.liveCount = 0;
    }
    while (this.resolvers.length > 0) {
      this.resolvers.shift()({
        value: void 0,
        done: true
      });
    }
  }
  next() {
    if (this.buf.length > 0) {
      const entry = this.buf.shift();
      if (!entry.forced) this.liveCount -= 1;
      return Promise.resolve({ value: entry.value, done: false });
    }
    if (this.closed) {
      return Promise.resolve({
        value: void 0,
        done: true
      });
    }
    return new Promise((resolve3) => this.resolvers.push(resolve3));
  }
};

// packages/cli/src/serve/event-bus.ts
init_esbuild_shims();

// packages/acp-bridge/src/bridgeErrors.ts
init_esbuild_shims();

// packages/acp-bridge/src/workspacePaths.ts
init_esbuild_shims();
import { realpathSync } from "node:fs";
import * as path from "node:path";
function canonicalizeWorkspace(p) {
  const resolved = path.resolve(p);
  try {
    return realpathSync.native(resolved);
  } catch (err) {
    if (err && typeof err === "object" && err.code === "ENOENT") {
      return resolved;
    }
    throw err;
  }
}
__name(canonicalizeWorkspace, "canonicalizeWorkspace");
var MAX_WORKSPACE_PATH_LENGTH = 4096;

// packages/acp-bridge/src/bridgeErrors.ts
var NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE = "Not currently generating";
function isNotCurrentlyGeneratingCancelError(err) {
  if (!err || typeof err !== "object") return false;
  const maybe = err;
  if (isNotCurrentlyGeneratingText(maybe.message)) return true;
  if (!maybe.data || typeof maybe.data !== "object") return false;
  return isNotCurrentlyGeneratingText(
    maybe.data.details
  );
}
__name(isNotCurrentlyGeneratingCancelError, "isNotCurrentlyGeneratingCancelError");
function isNotCurrentlyGeneratingText(value) {
  return typeof value === "string" && /\bnot currently generating\b/i.test(value);
}
__name(isNotCurrentlyGeneratingText, "isNotCurrentlyGeneratingText");
var SessionNotFoundError = class extends Error {
  static {
    __name(this, "SessionNotFoundError");
  }
  sessionId;
  constructor(sessionId, extra) {
    super(`No session with id "${sessionId}"` + (extra ? `. ${extra}` : ""));
    this.name = "SessionNotFoundError";
    this.sessionId = sessionId;
  }
};
var RestoreInProgressError = class extends Error {
  static {
    __name(this, "RestoreInProgressError");
  }
  sessionId;
  activeAction;
  requestedAction;
  constructor(sessionId, activeAction, requestedAction) {
    super(
      `Session "${sessionId}" is already being restored via session/${activeAction}; retry session/${requestedAction} after it completes`
    );
    this.name = "RestoreInProgressError";
    this.sessionId = sessionId;
    this.activeAction = activeAction;
    this.requestedAction = requestedAction;
  }
};
var InvalidSessionScopeError = class extends Error {
  static {
    __name(this, "InvalidSessionScopeError");
  }
  sessionScope;
  constructor(sessionScope) {
    super(
      `Invalid sessionScope: ${JSON.stringify(sessionScope)}. Expected 'single' or 'thread'.`
    );
    this.name = "InvalidSessionScopeError";
    this.sessionScope = sessionScope;
  }
};
var SessionLimitExceededError = class extends Error {
  static {
    __name(this, "SessionLimitExceededError");
  }
  limit;
  constructor(limit) {
    super(`Session limit reached (${limit})`);
    this.name = "SessionLimitExceededError";
    this.limit = limit;
  }
};
var PromptQueueFullError = class extends Error {
  static {
    __name(this, "PromptQueueFullError");
  }
  limit;
  pendingCount;
  sessionId;
  constructor(limit, pendingCount, sessionId) {
    super(
      `Prompt queue full for session "${sessionId}" (${pendingCount}/${limit} pending)`
    );
    this.name = "PromptQueueFullError";
    this.limit = limit;
    this.pendingCount = pendingCount;
    this.sessionId = sessionId;
  }
};
var WorkspaceMismatchError = class extends Error {
  static {
    __name(this, "WorkspaceMismatchError");
  }
  bound;
  requested;
  constructor(bound, requested) {
    const safeRequested = requested.length > MAX_WORKSPACE_PATH_LENGTH ? `${requested.slice(0, MAX_WORKSPACE_PATH_LENGTH)}\u2026[truncated]` : requested;
    super(
      `Workspace mismatch: daemon is bound to "${bound}" but request asked for "${safeRequested}". Each \`qwen serve\` daemon binds to exactly one workspace; start a separate daemon for "${safeRequested}" (or route the request to one via an orchestrator).`
    );
    this.name = "WorkspaceMismatchError";
    this.bound = bound;
    this.requested = safeRequested;
  }
};
var InvalidClientIdError = class extends Error {
  static {
    __name(this, "InvalidClientIdError");
  }
  sessionId;
  clientId;
  constructor(sessionId, clientId) {
    super(`Client id "${clientId}" is not registered for session ${sessionId}`);
    this.name = "InvalidClientIdError";
    this.sessionId = sessionId;
    this.clientId = clientId;
  }
};
var SessionShellDisabledError = class extends Error {
  static {
    __name(this, "SessionShellDisabledError");
  }
  constructor() {
    super("Direct session shell is disabled for this daemon");
    this.name = "SessionShellDisabledError";
  }
};
var SessionShellClientRequiredError = class extends Error {
  static {
    __name(this, "SessionShellClientRequiredError");
  }
  constructor() {
    super("Direct session shell requires a session-bound client id");
    this.name = "SessionShellClientRequiredError";
  }
};
var InvalidPermissionOptionError = class extends Error {
  static {
    __name(this, "InvalidPermissionOptionError");
  }
  requestId;
  optionId;
  constructor(requestId, optionId) {
    super(
      `Permission ${requestId}: optionId "${optionId}" is not in the set of options the agent offered.`
    );
    this.name = "InvalidPermissionOptionError";
    this.requestId = requestId;
    this.optionId = optionId;
  }
};
var InvalidSessionMetadataError = class extends Error {
  static {
    __name(this, "InvalidSessionMetadataError");
  }
  field;
  constructor(field, reason) {
    super(`Invalid session metadata: ${field} ${reason}`);
    this.name = "InvalidSessionMetadataError";
    this.field = field;
  }
};
var PermissionPolicyNotImplementedError = class extends Error {
  static {
    __name(this, "PermissionPolicyNotImplementedError");
  }
  policy;
  constructor(policy) {
    super(
      `Permission policy "${policy}" is declared in the contract but not yet implemented in this daemon build.`
    );
    this.name = "PermissionPolicyNotImplementedError";
    this.policy = policy;
  }
};
var CancelSentinelCollisionError = class extends Error {
  static {
    __name(this, "CancelSentinelCollisionError");
  }
  requestId;
  sentinel;
  constructor(requestId, sentinel) {
    super(
      `Permission ${requestId}: agent-declared optionId set contains the cancel-vote sentinel "${sentinel}", which would prevent the daemon from disambiguating cancel intent from a real vote.`
    );
    this.name = "CancelSentinelCollisionError";
    this.requestId = requestId;
    this.sentinel = sentinel;
  }
};
var PermissionForbiddenError = class extends Error {
  static {
    __name(this, "PermissionForbiddenError");
  }
  requestId;
  sessionId;
  reason;
  constructor(requestId, sessionId, reason) {
    super(
      `Permission ${requestId} on session ${sessionId}: vote rejected by policy (${reason}).`
    );
    this.name = "PermissionForbiddenError";
    this.requestId = requestId;
    this.sessionId = sessionId;
    this.reason = reason;
  }
};
var WorkspaceInitConflictError = class extends Error {
  static {
    __name(this, "WorkspaceInitConflictError");
  }
  path;
  existingSize;
  constructor(path9, existingSize) {
    super(
      `Workspace file ${path9} already exists (${existingSize} bytes); pass {force: true} to overwrite.`
    );
    this.name = "WorkspaceInitConflictError";
    this.path = path9;
    this.existingSize = existingSize;
  }
};
var WorkspaceInitPathEscapeError = class extends Error {
  static {
    __name(this, "WorkspaceInitPathEscapeError");
  }
  filename;
  boundWorkspace;
  constructor(filename, boundWorkspace) {
    super(
      `Configured workspace context filename ${JSON.stringify(filename)} resolves outside the bound workspace ${JSON.stringify(boundWorkspace)}. Refusing to write.`
    );
    this.name = "WorkspaceInitPathEscapeError";
    this.filename = filename;
    this.boundWorkspace = boundWorkspace;
  }
};
var WorkspaceInitSymlinkError = class extends Error {
  static {
    __name(this, "WorkspaceInitSymlinkError");
  }
  target;
  kind;
  constructor(target, kind, detail) {
    super(detail);
    this.name = "WorkspaceInitSymlinkError";
    this.target = target;
    this.kind = kind;
  }
};
var WorkspaceInitRaceError = class extends Error {
  static {
    __name(this, "WorkspaceInitRaceError");
  }
  target;
  kind;
  constructor(target, kind, detail) {
    super(detail);
    this.name = "WorkspaceInitRaceError";
    this.target = target;
    this.kind = kind;
  }
};
var McpServerNotFoundError = class extends Error {
  static {
    __name(this, "McpServerNotFoundError");
  }
  serverName;
  constructor(serverName) {
    super(`MCP server not configured: ${JSON.stringify(serverName)}`);
    this.name = "McpServerNotFoundError";
    this.serverName = serverName;
  }
};
var McpServerRestartFailedError = class extends Error {
  static {
    __name(this, "McpServerRestartFailedError");
  }
  serverName;
  mcpStatus;
  constructor(serverName, mcpStatus) {
    super(
      `MCP server ${JSON.stringify(serverName)} did not reach a connected state after restart (status: ${mcpStatus}).`
    );
    this.name = "McpServerRestartFailedError";
    this.serverName = serverName;
    this.mcpStatus = mcpStatus;
  }
};
var SessionBusyError = class extends Error {
  static {
    __name(this, "SessionBusyError");
  }
  sessionId;
  constructor(sessionId, message) {
    super(message ?? `Session ${sessionId} is busy (prompt running)`);
    this.name = "SessionBusyError";
    this.sessionId = sessionId;
  }
};
var InvalidRewindTargetError = class extends Error {
  static {
    __name(this, "InvalidRewindTargetError");
  }
  sessionId;
  constructor(sessionId, message) {
    super(
      message ?? `Cannot rewind to the requested turn (compressed or does not exist)`
    );
    this.name = "InvalidRewindTargetError";
    this.sessionId = sessionId;
  }
};
var BranchWhilePromptActiveError = class extends Error {
  static {
    __name(this, "BranchWhilePromptActiveError");
  }
  sessionId;
  constructor(sessionId) {
    super(`Cannot branch session ${sessionId}: a prompt is currently active`);
    this.name = "BranchWhilePromptActiveError";
    this.sessionId = sessionId;
  }
};

// packages/acp-bridge/src/status.ts
init_esbuild_shims();
var STATUS_SCHEMA_VERSION = 1;
var SERVE_ERROR_KINDS = [
  "missing_binary",
  "blocked_egress",
  "auth_env_error",
  "init_timeout",
  "protocol_error",
  "missing_file",
  "parse_error",
  "stat_failed",
  // Budget refusal under `--mcp-budget-mode=enforce`.
  // Surfaced on per-server `mcp_server` cells (refused at discovery)
  // and on the workspace-level `mcp_budget` cell (any refusal this pass).
  "budget_exhausted",
  // Runtime MCP mutation routes
  "mcp_budget_would_exceed",
  "mcp_server_spawn_failed",
  "invalid_config",
  // Prompt deadline + writer idle timeout
  "prompt_deadline_exceeded",
  "writer_idle_timeout"
];
var BridgeTimeoutError = class extends Error {
  static {
    __name(this, "BridgeTimeoutError");
  }
  label;
  timeoutMs;
  constructor(label, timeoutMs) {
    super(`AcpSessionBridge ${label} timed out after ${timeoutMs}ms`);
    this.name = "BridgeTimeoutError";
    this.label = label;
    this.timeoutMs = timeoutMs;
  }
};
var BridgeChannelClosedError = class extends Error {
  static {
    __name(this, "BridgeChannelClosedError");
  }
  context;
  constructor(context) {
    super(`agent channel closed ${context}`);
    this.name = "BridgeChannelClosedError";
    this.context = context;
  }
};
var MissingCliEntryError = class extends Error {
  static {
    __name(this, "MissingCliEntryError");
  }
  constructor() {
    super(
      "Cannot determine CLI entry path for spawning the ACP child: process.argv[1] is empty and QWEN_CLI_ENTRY is unset. Set QWEN_CLI_ENTRY to the absolute path of the qwen entry script (e.g. `export QWEN_CLI_ENTRY=$(which qwen)`) to override."
    );
    this.name = "MissingCliEntryError";
  }
};
var SERVE_STATUS_EXT_METHODS = {
  workspaceMcp: "qwen/status/workspace/mcp",
  workspaceMcpTools: "qwen/status/workspace/mcp/tools",
  workspaceSkills: "qwen/status/workspace/skills",
  workspaceTools: "qwen/status/workspace/tools",
  workspaceProviders: "qwen/status/workspace/providers",
  workspaceMemory: "qwen/status/workspace/memory",
  workspaceAgents: "qwen/status/workspace/agents",
  workspacePreflight: "qwen/status/workspace/preflight",
  sessionContext: "qwen/status/session/context",
  sessionContextUsage: "qwen/status/session/context_usage",
  sessionSupportedCommands: "qwen/status/session/supported_commands",
  sessionTasks: "qwen/status/session/tasks",
  sessionStats: "qwen/status/session/stats",
  sessionRewindSnapshots: "qwen/status/session/rewind_snapshots",
  workspaceHooks: "qwen/status/workspace/hooks",
  sessionHooks: "qwen/status/session/hooks",
  workspaceExtensions: "qwen/status/workspace/extensions"
};
var SERVE_CONTROL_EXT_METHODS = {
  sessionClose: "qwen/control/session/close",
  sessionApprovalMode: "qwen/control/session/approval_mode",
  sessionBranch: "qwen/control/session/branch",
  sessionForkAgent: "qwen/control/session/fork_agent",
  sessionRecap: "qwen/control/session/recap",
  sessionBtw: "qwen/control/session/btw",
  sessionShellHistory: "qwen/control/session/shell_history",
  sessionLanguage: "qwen/control/session/language",
  sessionRewind: "qwen/control/session/rewind",
  sessionTitle: "qwen/control/session/title",
  workspaceMcpRestart: "qwen/control/workspace/mcp/restart",
  workspaceMcpManage: "qwen/control/workspace/mcp/manage",
  workspaceAgentGenerate: "qwen/control/workspace/agents/generate",
  // Runtime MCP server mutation ext-methods
  sessionTaskCancel: "qwen/control/session/task/cancel",
  sessionGoalClear: "qwen/control/session/goal/clear",
  workspaceMcpRuntimeAdd: "qwen/control/workspace/mcp/runtime-add",
  workspaceMcpRuntimeRemove: "qwen/control/workspace/mcp/runtime-remove",
  workspaceReload: "qwen/control/workspace/reload",
  workspaceExtensionsRefresh: "qwen/control/workspace/extensions/refresh"
};
var IDLE_HOOK_EVENTS = {
  PreToolUse: { description: "Before tool execution", matcherKind: "toolName" },
  PostToolUse: { description: "After tool execution", matcherKind: "toolName" },
  PostToolUseFailure: {
    description: "After tool execution fails",
    matcherKind: "toolName"
  },
  PostToolBatch: { description: "After a batch of tool calls resolves" },
  Notification: {
    description: "When notifications are sent",
    matcherKind: "notificationType"
  },
  UserPromptSubmit: { description: "When the user submits a prompt" },
  UserPromptExpansion: {
    description: "When a slash command expands into a prompt",
    matcherKind: "commandName"
  },
  SessionStart: {
    description: "When a new session is started",
    matcherKind: "sessionTrigger"
  },
  Stop: { description: "Right before Qwen Code concludes its response" },
  SubagentStart: {
    description: "When a subagent is started",
    matcherKind: "agentType"
  },
  SubagentStop: {
    description: "Right before a subagent concludes its response",
    matcherKind: "agentType"
  },
  PreCompact: {
    description: "Before conversation compaction",
    matcherKind: "trigger"
  },
  PostCompact: {
    description: "After conversation compaction",
    matcherKind: "trigger"
  },
  SessionEnd: {
    description: "When a session is ending",
    matcherKind: "sessionTrigger"
  },
  PermissionRequest: {
    description: "When a permission dialog is displayed",
    matcherKind: "toolName"
  },
  PermissionDenied: {
    description: "When a tool call is denied",
    matcherKind: "toolName"
  },
  StopFailure: {
    description: "When the turn ends due to an API error",
    matcherKind: "error"
  },
  TodoCreated: { description: "When a new todo item is created" },
  TodoCompleted: { description: "When a todo item is marked as completed" },
  InstructionsLoaded: {
    description: "When an instruction or context file is loaded",
    matcherKind: "filePath"
  }
};
function createIdleWorkspaceExtensionsStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    extensions: []
  };
}
__name(createIdleWorkspaceExtensionsStatus, "createIdleWorkspaceExtensionsStatus");
function createIdleWorkspaceHooksStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    disabled: false,
    hooks: [],
    events: IDLE_HOOK_EVENTS
  };
}
__name(createIdleWorkspaceHooksStatus, "createIdleWorkspaceHooksStatus");
function createIdleWorkspaceMemoryStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    files: [],
    totalBytes: 0,
    fileCount: 0,
    ruleCount: 0
  };
}
__name(createIdleWorkspaceMemoryStatus, "createIdleWorkspaceMemoryStatus");
function createIdleWorkspaceMcpStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    discoveryState: "not_started",
    servers: [],
    clientCount: 0,
    budgetMode: "off",
    budgets: []
  };
}
__name(createIdleWorkspaceMcpStatus, "createIdleWorkspaceMcpStatus");
function createIdleWorkspaceSkillsStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    skills: []
  };
}
__name(createIdleWorkspaceSkillsStatus, "createIdleWorkspaceSkillsStatus");
function createIdleWorkspaceProvidersStatus(workspaceCwd) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: false,
    providers: []
  };
}
__name(createIdleWorkspaceProvidersStatus, "createIdleWorkspaceProvidersStatus");
function createIdleEnvStatus(workspaceCwd, acpChannelLive) {
  return {
    v: STATUS_SCHEMA_VERSION,
    workspaceCwd,
    initialized: true,
    acpChannelLive,
    cells: []
  };
}
__name(createIdleEnvStatus, "createIdleEnvStatus");
var ACP_PREFLIGHT_KINDS = [
  "auth",
  "mcp_discovery",
  "skills",
  "providers",
  "tool_registry",
  "egress"
];
function createIdleAcpPreflightCells() {
  return ACP_PREFLIGHT_KINDS.map((kind) => ({
    kind,
    status: "not_started",
    locality: "acp",
    hint: "spawn a session to populate"
  }));
}
__name(createIdleAcpPreflightCells, "createIdleAcpPreflightCells");
var SKILL_PARSE_CODES = /* @__PURE__ */ new Set([
  "PARSE_ERROR",
  "INVALID_CONFIG",
  "INVALID_NAME"
]);
var SKILL_FILE_CODES = /* @__PURE__ */ new Set([
  "FILE_ERROR",
  "NOT_FOUND"
]);
var FS_MISSING_CODES = /* @__PURE__ */ new Set([
  "ENOENT",
  "EACCES",
  "EPERM"
]);
var MODEL_CONFIG_ERROR_NAMES = /* @__PURE__ */ new Set([
  "StrictMissingCredentialsError",
  "StrictMissingModelIdError",
  "MissingApiKeyError",
  "MissingModelError",
  "MissingBaseUrlError",
  "MissingAnthropicBaseUrlEnvError"
]);
function mapDomainErrorToErrorKind(err) {
  if (err instanceof BridgeTimeoutError) return "init_timeout";
  if (err instanceof BridgeChannelClosedError) return "protocol_error";
  if (err instanceof MissingCliEntryError) return "missing_binary";
  if (err instanceof SkillError || err?.name === "SkillError") {
    const code2 = err.code;
    if (code2 && SKILL_PARSE_CODES.has(code2)) return "parse_error";
    if (code2 && SKILL_FILE_CODES.has(code2)) return "missing_file";
    return void 0;
  }
  if (err instanceof SyntaxError) return "parse_error";
  if (!(err instanceof Error)) return void 0;
  if (err.name === "TrustGateError") return "auth_env_error";
  if (MODEL_CONFIG_ERROR_NAMES.has(err.name)) return "auth_env_error";
  const code = err.code;
  if (typeof code === "string" && FS_MISSING_CODES.has(code)) {
    return "missing_file";
  }
  return void 0;
}
__name(mapDomainErrorToErrorKind, "mapDomainErrorToErrorKind");

// packages/cli/src/serve/status.ts
init_esbuild_shims();

// packages/cli/src/config/trustedFolders.ts
init_esbuild_shims();
import * as fs3 from "node:fs";
import * as path2 from "node:path";
var import_comment_json2 = __toESM(require_src2(), 1);
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/utils/commentJson.ts
init_esbuild_shims();
var import_comment_json = __toESM(require_src2(), 1);
import * as fs2 from "node:fs";

// packages/cli/src/utils/writeWithBackup.ts
init_esbuild_shims();
import * as fs from "node:fs";
function writeWithBackupSync(targetPath, content, options = {}) {
  const { backupSuffix = ".orig", encoding = "utf-8" } = options;
  const tempPath = `${targetPath}.tmp`;
  const backupPath = `${targetPath}${backupSuffix}`;
  let backupCreated = false;
  try {
    if (fs.existsSync(tempPath)) {
      fs.unlinkSync(tempPath);
    }
  } catch (_e) {
  }
  try {
    fs.writeFileSync(tempPath, content, { encoding, flush: true });
    if (fs.existsSync(targetPath)) {
      const targetStat = fs.statSync(targetPath);
      if (targetStat.isDirectory()) {
        try {
          fs.unlinkSync(tempPath);
        } catch (_e) {
        }
        throw new Error(
          `Cannot write to '${targetPath}' because it is a directory`
        );
      }
      try {
        fs.renameSync(targetPath, backupPath);
        backupCreated = true;
      } catch (backupError) {
        try {
          fs.unlinkSync(tempPath);
        } catch (_e) {
        }
        throw new Error(
          `Failed to backup existing file: ${backupError instanceof Error ? backupError.message : String(backupError)}`
        );
      }
    }
    try {
      fs.renameSync(tempPath, targetPath);
      if (backupCreated) {
        try {
          fs.unlinkSync(backupPath);
        } catch (_e) {
        }
      }
    } catch (renameError) {
      let restoreFailedMessage;
      let backupExisted = false;
      if (fs.existsSync(backupPath)) {
        backupExisted = true;
        try {
          fs.renameSync(backupPath, targetPath);
        } catch (restoreError) {
          restoreFailedMessage = restoreError instanceof Error ? restoreError.message : String(restoreError);
        }
      }
      const writeFailureMessage = renameError instanceof Error ? renameError.message : String(renameError);
      if (restoreFailedMessage) {
        throw new Error(
          `Failed to write file: ${writeFailureMessage}. Automatic restore failed: ${restoreFailedMessage}. Manual recovery may be required using backup file '${backupPath}'.`
        );
      }
      if (backupExisted) {
        throw new Error(
          `Failed to write file: ${writeFailureMessage}. Target was automatically restored from backup '${backupPath}'.`
        );
      }
      throw new Error(
        `Failed to write file: ${writeFailureMessage}. No backup file was available for restoration.`
      );
    }
  } catch (error) {
    try {
      if (fs.existsSync(tempPath)) {
        fs.unlinkSync(tempPath);
      }
    } catch (_e) {
    }
    throw error;
  }
}
__name(writeWithBackupSync, "writeWithBackupSync");

// packages/cli/src/utils/commentJson.ts
function updateSettingsFilePreservingFormat(filePath, updates, sync = false, replacePath = []) {
  if (!fs2.existsSync(filePath)) {
    const content = (0, import_comment_json.stringify)(updates, null, 2);
    writeWithBackupSync(filePath, content);
    return true;
  }
  const originalContent = fs2.readFileSync(filePath, "utf-8");
  let parsed;
  try {
    parsed = (0, import_comment_json.parse)(originalContent);
  } catch (_error) {
    writeStderrLine("Error parsing settings file.");
    writeStderrLine(
      `Settings file may be corrupted: ${_error instanceof Error ? _error.message : String(_error)}`
    );
    return false;
  }
  const updatedStructure = applyUpdates(parsed, updates, sync, replacePath);
  const updatedContent = (0, import_comment_json.stringify)(updatedStructure, null, 2);
  try {
    (0, import_comment_json.parse)(updatedContent);
  } catch (validationError) {
    writeStderrLine(
      "Error: Refusing to write settings file \u2014 the result would not be valid JSON."
    );
    writeStderrLine(
      validationError instanceof Error ? validationError.message : String(validationError)
    );
    return false;
  }
  writeWithBackupSync(filePath, updatedContent);
  return true;
}
__name(updateSettingsFilePreservingFormat, "updateSettingsFilePreservingFormat");
function applyUpdates(current, updates, sync = false, replacePath = [], currentPath = []) {
  const result = current;
  if (sync) {
    const keysToRemove = Object.keys(result).filter((key) => !(key in updates));
    for (const key of keysToRemove) {
      delete result[key];
    }
  }
  for (const key of Object.getOwnPropertyNames(updates)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const value = updates[key];
    const nextPath = [...currentPath, key];
    const valueIsObject = typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0;
    if (pathsEqual(nextPath, replacePath)) {
      result[key] = valueIsObject ? applyUpdates({}, value) : value;
      continue;
    }
    if (valueIsObject && (typeof result[key] !== "object" || result[key] === null || Array.isArray(result[key]))) {
      result[key] = applyUpdates(
        {},
        value,
        sync,
        replacePath,
        nextPath
      );
    } else if (valueIsObject && typeof result[key] === "object" && result[key] !== null && !Array.isArray(result[key])) {
      result[key] = applyUpdates(
        result[key],
        value,
        sync,
        replacePath,
        nextPath
      );
    } else {
      result[key] = value;
    }
  }
  return result;
}
__name(applyUpdates, "applyUpdates");
function pathsEqual(left, right) {
  return left.length === right.length && left.every((segment, index) => segment === right[index]);
}
__name(pathsEqual, "pathsEqual");

// packages/cli/src/config/trustedFolders.ts
var TRUSTED_FOLDERS_FILENAME = "trustedFolders.json";
function getTrustedFoldersPath() {
  if (process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"]) {
    return process.env["QWEN_CODE_TRUSTED_FOLDERS_PATH"];
  }
  return path2.join(Storage.getGlobalQwenDir(), TRUSTED_FOLDERS_FILENAME);
}
__name(getTrustedFoldersPath, "getTrustedFoldersPath");
var LoadedTrustedFolders = class {
  constructor(user, errors) {
    this.user = user;
    this.errors = errors;
  }
  static {
    __name(this, "LoadedTrustedFolders");
  }
  get rules() {
    return Object.entries(this.user.config).map(([path9, trustLevel]) => ({
      path: path9,
      trustLevel
    }));
  }
  /**
   * Returns true or false if the path should be "trusted". This function
   * should only be invoked when the folder trust setting is active.
   *
   * @param location path
   * @returns
   */
  isPathTrusted(location) {
    const trustedPaths = [];
    const untrustedPaths = [];
    for (const rule of this.rules) {
      switch (rule.trustLevel) {
        case "TRUST_FOLDER" /* TRUST_FOLDER */:
          trustedPaths.push(rule.path);
          break;
        case "TRUST_PARENT" /* TRUST_PARENT */:
          trustedPaths.push(path2.dirname(rule.path));
          break;
        case "DO_NOT_TRUST" /* DO_NOT_TRUST */:
          untrustedPaths.push(rule.path);
          break;
        default:
          break;
      }
    }
    for (const trustedPath of trustedPaths) {
      if (isWithinRoot(location, trustedPath)) {
        return true;
      }
    }
    for (const untrustedPath of untrustedPaths) {
      if (path2.normalize(location) === path2.normalize(untrustedPath)) {
        return false;
      }
    }
    return void 0;
  }
  setValue(path9, trustLevel) {
    this.user.config[path9] = trustLevel;
    saveTrustedFolders(this.user);
  }
};
var loadedTrustedFolders;
function loadTrustedFolders() {
  if (loadedTrustedFolders) {
    return loadedTrustedFolders;
  }
  const errors = [];
  let userConfig = {};
  const userPath = getTrustedFoldersPath();
  try {
    if (fs3.existsSync(userPath)) {
      const content = fs3.readFileSync(userPath, "utf-8");
      const parsed = JSON.parse((0, import_strip_json_comments.default)(content));
      if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
        errors.push({
          message: "Trusted folders file is not a valid JSON object.",
          path: userPath
        });
      } else {
        userConfig = parsed;
      }
    }
  } catch (error) {
    errors.push({
      message: getErrorMessage(error),
      path: userPath
    });
  }
  loadedTrustedFolders = new LoadedTrustedFolders(
    { path: userPath, config: userConfig },
    errors
  );
  return loadedTrustedFolders;
}
__name(loadTrustedFolders, "loadTrustedFolders");
function saveTrustedFolders(trustedFoldersFile) {
  try {
    const dirPath = path2.dirname(trustedFoldersFile.path);
    if (!fs3.existsSync(dirPath)) {
      fs3.mkdirSync(dirPath, { recursive: true });
    }
    let content = (0, import_comment_json2.stringify)(trustedFoldersFile.config, null, 2);
    if (fs3.existsSync(trustedFoldersFile.path)) {
      try {
        const originalContent = fs3.readFileSync(
          trustedFoldersFile.path,
          "utf-8"
        );
        const parsed = (0, import_comment_json2.parse)(originalContent);
        if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed) || parsed instanceof String || parsed instanceof Number || parsed instanceof Boolean) {
          throw new Error("trusted folders file is not a JSON object");
        }
        const updated = applyUpdates(
          parsed,
          trustedFoldersFile.config,
          true
        );
        const preservedContent = (0, import_comment_json2.stringify)(updated, null, 2);
        (0, import_comment_json2.parse)(preservedContent);
        content = preservedContent;
      } catch (error) {
        writeStderrLine(
          `Falling back to clean rewrite for trusted folders: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
    atomicWriteFileSync(
      trustedFoldersFile.path,
      content,
      // noFollow: refuse to follow any pre-placed symlink at the
      // config path — a redirected write could either leak the
      // trusted-folder list to an attacker target or leave the user's
      // real config silently stale. Matches the credential write
      // sites' security posture (sharedTokenManager, oauth-token-storage,
      // file-token-storage all use noFollow:true).
      { encoding: "utf-8", mode: 384, forceMode: true, noFollow: true }
    );
  } catch (error) {
    writeStderrLine("Error saving trusted folders file.");
    writeStderrLine(error instanceof Error ? error.message : String(error));
  }
}
__name(saveTrustedFolders, "saveTrustedFolders");
function isFolderTrustEnabled(settings) {
  const folderTrustSetting = settings.security?.folderTrust?.enabled ?? false;
  return folderTrustSetting;
}
__name(isFolderTrustEnabled, "isFolderTrustEnabled");
function getWorkspaceTrustFromLocalConfig(trustConfig) {
  const folders = loadTrustedFolders();
  if (trustConfig) {
    folders.user.config = trustConfig;
  }
  if (folders.errors.length > 0) {
    const errorMessages = folders.errors.map(
      (error) => `Error in ${error.path}: ${error.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file and try again.`
    );
  }
  const isTrusted = folders.isPathTrusted(process.cwd());
  return {
    isTrusted,
    source: isTrusted !== void 0 ? "file" : void 0
  };
}
__name(getWorkspaceTrustFromLocalConfig, "getWorkspaceTrustFromLocalConfig");
function isWorkspaceTrusted(settings, trustConfig) {
  if (!isFolderTrustEnabled(settings)) {
    return { isTrusted: true, source: void 0 };
  }
  const ideTrust = ideContextStore.get()?.workspaceState?.isTrusted;
  if (ideTrust !== void 0) {
    return { isTrusted: ideTrust, source: "ide" };
  }
  return getWorkspaceTrustFromLocalConfig(trustConfig);
}
__name(isWorkspaceTrusted, "isWorkspaceTrusted");

// packages/cli/src/utils/languageUtils.ts
init_esbuild_shims();
import * as fs4 from "node:fs";
import * as path3 from "node:path";
var LLM_OUTPUT_LANGUAGE_RULE_FILENAME = "output-language.md";
var LLM_OUTPUT_LANGUAGE_MARKER_PREFIX = "qwen-code:llm-output-language:";
var OUTPUT_LANGUAGE_AUTO = "auto";
function isAutoLanguage(value) {
  return !value || value.toLowerCase() === OUTPUT_LANGUAGE_AUTO;
}
__name(isAutoLanguage, "isAutoLanguage");
function normalizeOutputLanguage(language) {
  const normalized = language.trim().replace(/_/g, "-").toLowerCase();
  const knownLanguageName = SUPPORTED_LANGUAGES.find(
    (supportedLanguage) => supportedLanguage.fullName.toLowerCase() === normalized
  );
  if (knownLanguageName) {
    return knownLanguageName.fullName;
  }
  const knownLocaleCode = SUPPORTED_LANGUAGES.some((supportedLanguage) => {
    const code = supportedLanguage.code.toLowerCase();
    const id = supportedLanguage.id.toLowerCase();
    return normalized === code || normalized === id || normalized.startsWith(`${code}-`) || normalized.startsWith(`${id}-`) || normalized.startsWith(`${code}.`) || normalized.startsWith(`${id}.`) || normalized.startsWith(`${code}@`) || normalized.startsWith(`${id}@`);
  });
  if (!knownLocaleCode) {
    return language;
  }
  return getLanguageNameFromLocale(normalized);
}
__name(normalizeOutputLanguage, "normalizeOutputLanguage");
function resolveOutputLanguage(value) {
  if (isAutoLanguage(value)) {
    const detectedLocale = detectSystemLanguage();
    return getLanguageNameFromLocale(detectedLocale);
  }
  return normalizeOutputLanguage(value);
}
__name(resolveOutputLanguage, "resolveOutputLanguage");
function getOutputLanguageFilePath() {
  return path3.join(
    Storage.getGlobalQwenDir(),
    LLM_OUTPUT_LANGUAGE_RULE_FILENAME
  );
}
__name(getOutputLanguageFilePath, "getOutputLanguageFilePath");
function sanitizeForMarker(language) {
  return language.replace(/[\r\n]/g, " ").replace(/--!?>/g, "").replace(/--/g, "");
}
__name(sanitizeForMarker, "sanitizeForMarker");
function generateOutputLanguageFileContent(language) {
  const safeLanguage = sanitizeForMarker(language);
  return `# Output language preference: ${language}
<!-- ${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX} ${safeLanguage} -->

## Rule
You MUST always respond in **${language}** regardless of the user's input language.
This is a mandatory requirement, not a preference.

## Exception
If the user **explicitly** requests a response in a specific language (e.g., "please reply in English", "\u7528\u4E2D\u6587\u56DE\u7B54"), switch to the user's requested language for the remainder of the conversation.

## Keep technical artifacts unchanged
Do **not** translate or rewrite:
- Code blocks, CLI commands, file paths, stack traces, logs, JSON keys, identifiers
- Exact quoted text from the user (keep quotes verbatim)

## Tool / system outputs
Raw tool/system outputs may contain fixed-format English. Preserve them verbatim, and if needed, add a short **${language}** explanation below.
`;
}
__name(generateOutputLanguageFileContent, "generateOutputLanguageFileContent");
function parseOutputLanguageFromContent(content) {
  const markerRegex = new RegExp(
    String.raw`<!--\s*${LLM_OUTPUT_LANGUAGE_MARKER_PREFIX}\s*(.*?)\s*-->`,
    "i"
  );
  const markerMatch = content.match(markerRegex);
  if (markerMatch?.[1]?.trim()) {
    return markerMatch[1].trim();
  }
  const headingMatch = content.match(
    /^#.*?CRITICAL:\s*(.*?)\s+Output Language Rule\b/im
  );
  if (headingMatch?.[1]?.trim()) {
    return headingMatch[1].trim();
  }
  return null;
}
__name(parseOutputLanguageFromContent, "parseOutputLanguageFromContent");
function readOutputLanguageFromFile() {
  const filePath = getOutputLanguageFilePath();
  if (!fs4.existsSync(filePath)) {
    return null;
  }
  try {
    const content = fs4.readFileSync(filePath, "utf-8");
    return parseOutputLanguageFromContent(content);
  } catch {
    return null;
  }
}
__name(readOutputLanguageFromFile, "readOutputLanguageFromFile");
function writeOutputLanguageFile(language, targetPath) {
  const filePath = targetPath ?? getOutputLanguageFilePath();
  const content = generateOutputLanguageFileContent(language);
  const dir = path3.dirname(filePath);
  fs4.mkdirSync(dir, { recursive: true });
  fs4.writeFileSync(filePath, content, "utf-8");
}
__name(writeOutputLanguageFile, "writeOutputLanguageFile");
function updateOutputLanguageFile(settingValue, targetPath) {
  const resolved = resolveOutputLanguage(settingValue);
  writeOutputLanguageFile(resolved, targetPath);
}
__name(updateOutputLanguageFile, "updateOutputLanguageFile");
function writeOutputLanguageAndRegisterPath(settingValue, config) {
  const targetPath = config?.getOutputLanguageFilePath();
  updateOutputLanguageFile(settingValue, targetPath);
  if (!targetPath) {
    config?.setOutputLanguageFilePath(getOutputLanguageFilePath());
  }
}
__name(writeOutputLanguageAndRegisterPath, "writeOutputLanguageAndRegisterPath");
function initializeLlmOutputLanguage(outputLanguage) {
  const currentFileLanguage = readOutputLanguageFromFile();
  if (currentFileLanguage) {
    return;
  }
  const resolved = resolveOutputLanguage(outputLanguage);
  writeOutputLanguageFile(resolved);
}
__name(initializeLlmOutputLanguage, "initializeLlmOutputLanguage");

// packages/cli/src/config/settings.ts
init_esbuild_shims();
var dotenv = __toESM(require_main(), 1);
import * as fs6 from "node:fs";
import * as path4 from "node:path";
import { homedir, platform } from "node:os";
import process2 from "node:process";
var import_strip_json_comments2 = __toESM(require_strip_json_comments(), 1);

// packages/cli/src/ui/themes/default-light.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/theme.ts
init_esbuild_shims();

// packages/cli/src/ui/themes/color-utils.ts
init_esbuild_shims();
var CSS_NAME_TO_HEX_MAP = {
  aliceblue: "#f0f8ff",
  antiquewhite: "#faebd7",
  aqua: "#00ffff",
  aquamarine: "#7fffd4",
  azure: "#f0ffff",
  beige: "#f5f5dc",
  bisque: "#ffe4c4",
  blanchedalmond: "#ffebcd",
  blueviolet: "#8a2be2",
  brown: "#a52a2a",
  burlywood: "#deb887",
  cadetblue: "#5f9ea0",
  chartreuse: "#7fff00",
  chocolate: "#d2691e",
  coral: "#ff7f50",
  cornflowerblue: "#6495ed",
  cornsilk: "#fff8dc",
  crimson: "#dc143c",
  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",
  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",
  maroon: "#800000",
  mediumaquamarine: "#66cdaa",
  mediumblue: "#0000cd",
  mediumorchid: "#ba55d3",
  mediumpurple: "#9370db",
  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: "#db7093",
  papayawhip: "#ffefd5",
  peachpuff: "#ffdab9",
  peru: "#cd853f",
  pink: "#ffc0cb",
  plum: "#dda0dd",
  powderblue: "#b0e0e6",
  purple: "#800080",
  rebeccapurple: "#663399",
  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",
  whitesmoke: "#f5f5f5",
  yellowgreen: "#9acd32"
};
var debugLogger = createDebugLogger("COLOR_UTILS");
var INK_SUPPORTED_NAMES = /* @__PURE__ */ new Set([
  "black",
  "red",
  "green",
  "yellow",
  "blue",
  "cyan",
  "magenta",
  "white",
  "gray",
  "grey",
  "blackbright",
  "redbright",
  "greenbright",
  "yellowbright",
  "bluebright",
  "cyanbright",
  "magentabright",
  "whitebright"
]);
function resolveColor(colorValue) {
  const lowerColor = colorValue.toLowerCase();
  if (lowerColor.startsWith("#")) {
    if (/^#[0-9A-Fa-f]{3}([0-9A-Fa-f]{3})?$/.test(colorValue)) {
      return lowerColor;
    } else {
      return void 0;
    }
  } else if (INK_SUPPORTED_NAMES.has(lowerColor)) {
    return lowerColor;
  } else if (CSS_NAME_TO_HEX_MAP[lowerColor]) {
    return CSS_NAME_TO_HEX_MAP[lowerColor];
  }
  debugLogger.warn(
    `[ColorUtils] Could not resolve color "${colorValue}" to an Ink-compatible format.`
  );
  return void 0;
}
__name(resolveColor, "resolveColor");
var INK_NAME_TO_HEX = {
  black: "#000000",
  red: "#ff0000",
  green: "#00ff00",
  yellow: "#ffff00",
  blue: "#0000ff",
  cyan: "#00ffff",
  magenta: "#ff00ff",
  white: "#ffffff",
  gray: "#808080",
  grey: "#808080",
  blackbright: "#808080",
  redbright: "#ff8080",
  greenbright: "#80ff80",
  yellowbright: "#ffff80",
  bluebright: "#8080ff",
  cyanbright: "#80ffff",
  magentabright: "#ff80ff",
  whitebright: "#ffffff"
};
function toHex(color) {
  const resolved = (resolveColor(color) ?? color).toLowerCase();
  if (resolved.startsWith("#")) {
    if (/^#[0-9a-f]{3}$/.test(resolved)) {
      return `#${resolved.slice(1).split("").map((c) => c + c).join("")}`;
    }
    if (/^#[0-9a-f]{6}$/.test(resolved)) {
      return resolved;
    }
    return void 0;
  }
  return INK_NAME_TO_HEX[resolved];
}
__name(toHex, "toHex");
function interpolateColor(color1, color2, factor) {
  if (factor <= 0) {
    return color1;
  }
  if (factor >= 1) {
    return color2;
  }
  const h1 = toHex(color1);
  const h2 = toHex(color2);
  if (!h1 || !h2) {
    return "";
  }
  const r1 = parseInt(h1.slice(1, 3), 16);
  const g1 = parseInt(h1.slice(3, 5), 16);
  const b1 = parseInt(h1.slice(5, 7), 16);
  const r2 = parseInt(h2.slice(1, 3), 16);
  const g2 = parseInt(h2.slice(3, 5), 16);
  const b2 = parseInt(h2.slice(5, 7), 16);
  const lerp = /* @__PURE__ */ __name((a, b) => Math.round(a + (b - a) * factor), "lerp");
  const toByte = /* @__PURE__ */ __name((n) => Math.max(0, Math.min(255, n)).toString(16).padStart(2, "0"), "toByte");
  return `#${toByte(lerp(r1, r2))}${toByte(lerp(g1, g2))}${toByte(lerp(b1, b2))}`;
}
__name(interpolateColor, "interpolateColor");
function subtleBandColor(bgColor, factor = 0.06) {
  const hex = toHex(bgColor);
  if (!hex) {
    return "";
  }
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  const isDark = (r * 299 + g * 587 + b * 114) / 1e3 < 128;
  const target = isDark ? "#ffffff" : "#000000";
  return interpolateColor(hex, target, factor);
}
__name(subtleBandColor, "subtleBandColor");
var _supportsTrueColor;
function supportsTrueColor() {
  if (_supportsTrueColor !== void 0) return _supportsTrueColor;
  const colorterm = process.env["COLORTERM"];
  if (colorterm === "truecolor" || colorterm === "24bit" || colorterm === "kmscon") {
    return _supportsTrueColor = true;
  }
  if (process.stdout.getColorDepth && process.stdout.getColorDepth() >= 24) {
    return _supportsTrueColor = true;
  }
  return _supportsTrueColor = false;
}
__name(supportsTrueColor, "supportsTrueColor");

// packages/cli/src/ui/themes/theme.ts
var lightTheme = {
  type: "light",
  Background: "#FAFAFA",
  Foreground: "",
  LightBlue: "#89BDCD",
  AccentBlue: "#3B82F6",
  AccentPurple: "#8B5CF6",
  AccentCyan: "#06B6D4",
  AccentGreen: "#3CA84B",
  AccentYellow: "#D5A40A",
  AccentRed: "#DD4C4C",
  AccentYellowDim: "#8B7000",
  AccentRedDim: "#993333",
  DiffAdded: "#C6EAD8",
  DiffRemoved: "#FFCCCC",
  Comment: "#008000",
  Gray: "#97a0b0",
  GradientColors: ["#4796E4", "#847ACE", "#C3677F"]
};
var darkTheme = {
  type: "dark",
  Background: "#1E1E2E",
  Foreground: "",
  LightBlue: "#ADD8E6",
  AccentBlue: "#89B4FA",
  AccentPurple: "#CBA6F7",
  AccentCyan: "#89DCEB",
  AccentGreen: "#A6E3A1",
  AccentYellow: "#F9E2AF",
  AccentRed: "#F38BA8",
  AccentYellowDim: "#8B7530",
  AccentRedDim: "#8B3A4A",
  DiffAdded: "#28350B",
  DiffRemoved: "#430000",
  Comment: "#6C7086",
  Gray: "#6C7086",
  GradientColors: ["#4796E4", "#847ACE", "#C3677F"]
};
var ansiTheme = {
  type: "ansi",
  Background: "black",
  Foreground: "white",
  LightBlue: "blue",
  AccentBlue: "blue",
  AccentPurple: "magenta",
  AccentCyan: "cyan",
  AccentGreen: "green",
  AccentYellow: "yellow",
  AccentRed: "red",
  AccentYellowDim: "yellow",
  AccentRedDim: "red",
  DiffAdded: "green",
  DiffRemoved: "red",
  Comment: "gray",
  Gray: "gray"
};
var Theme = class _Theme {
  /**
   * Creates a new Theme instance.
   * @param name The name of the theme.
   * @param rawMappings The raw CSSProperties mappings from a react-syntax-highlighter theme object.
   */
  constructor(name, type, rawMappings, colors, semanticColors) {
    this.name = name;
    this.type = type;
    this.colors = colors;
    this.semanticColors = semanticColors ?? {
      text: {
        primary: this.colors.Foreground,
        secondary: this.colors.Gray,
        link: this.colors.AccentBlue,
        accent: this.colors.AccentPurple,
        code: this.colors.LightBlue
      },
      background: {
        primary: this.colors.Background,
        diff: {
          added: this.colors.DiffAdded,
          removed: this.colors.DiffRemoved
        }
      },
      border: {
        default: this.colors.Gray,
        focused: this.colors.AccentBlue
      },
      ui: {
        comment: this.colors.Gray,
        symbol: this.colors.AccentCyan,
        gradient: this.colors.GradientColors
      },
      status: {
        error: this.colors.AccentRed,
        success: this.colors.AccentGreen,
        warning: this.colors.AccentYellow,
        errorDim: this.colors.AccentRedDim,
        warningDim: this.colors.AccentYellowDim
      }
    };
    this._colorMap = Object.freeze(this._buildColorMap(rawMappings));
    const rawDefaultColor = rawMappings["hljs"]?.color;
    this.defaultColor = (rawDefaultColor ? _Theme._resolveColor(rawDefaultColor) : void 0) ?? "";
  }
  static {
    __name(this, "Theme");
  }
  /**
   * The default foreground color for text when no specific highlight rule applies.
   * This is an Ink-compatible color string (hex or name).
   */
  defaultColor;
  /**
   * Stores the mapping from highlight.js class names (e.g., 'hljs-keyword')
   * to Ink-compatible color strings (hex or name).
   */
  _colorMap;
  semanticColors;
  /**
   * Gets the Ink-compatible color string for a given highlight.js class name.
   * @param hljsClass The highlight.js class name (e.g., 'hljs-keyword', 'hljs-string').
   * @returns The corresponding Ink color string (hex or name) if it exists.
   */
  getInkColor(hljsClass) {
    return this._colorMap[hljsClass];
  }
  /**
   * Resolves a CSS color value (name or hex) into an Ink-compatible color string.
   * @param colorValue The raw color string (e.g., 'blue', '#ff0000', 'darkkhaki').
   * @returns An Ink-compatible color string (hex or name), or undefined if not resolvable.
   */
  static _resolveColor(colorValue) {
    return resolveColor(colorValue);
  }
  /**
   * Builds the internal map from highlight.js class names to Ink-compatible color strings.
   * This method is protected and primarily intended for use by the constructor.
   * @param hljsTheme The raw CSSProperties mappings from a react-syntax-highlighter theme object.
   * @returns An Ink-compatible theme map (Record<string, string>).
   */
  _buildColorMap(hljsTheme) {
    const inkTheme = {};
    for (const key in hljsTheme) {
      if (!key.startsWith("hljs-") && key !== "hljs") {
        continue;
      }
      const style = hljsTheme[key];
      if (style?.color) {
        const resolvedColor = _Theme._resolveColor(style.color);
        if (resolvedColor !== void 0) {
          inkTheme[key] = resolvedColor;
        }
      }
    }
    return inkTheme;
  }
};
function createCustomTheme(customTheme) {
  const colors = {
    type: "custom",
    Background: customTheme.background?.primary ?? customTheme.Background ?? "",
    Foreground: customTheme.text?.primary ?? customTheme.Foreground ?? "",
    LightBlue: customTheme.text?.code ?? customTheme.LightBlue ?? "",
    AccentBlue: customTheme.text?.link ?? customTheme.AccentBlue ?? "",
    AccentPurple: customTheme.text?.accent ?? customTheme.AccentPurple ?? "",
    AccentCyan: customTheme.text?.link ?? customTheme.AccentCyan ?? "",
    AccentGreen: customTheme.status?.success ?? customTheme.AccentGreen ?? "",
    AccentYellow: customTheme.status?.warning ?? customTheme.AccentYellow ?? "",
    AccentRed: customTheme.status?.error ?? customTheme.AccentRed ?? "",
    AccentYellowDim: customTheme.status?.warningDim ?? customTheme.AccentYellowDim ?? "",
    AccentRedDim: customTheme.status?.errorDim ?? customTheme.AccentRedDim ?? "",
    DiffAdded: customTheme.background?.diff?.added ?? customTheme.DiffAdded ?? "",
    DiffRemoved: customTheme.background?.diff?.removed ?? customTheme.DiffRemoved ?? "",
    Comment: customTheme.ui?.comment ?? customTheme.Comment ?? "",
    Gray: customTheme.text?.secondary ?? customTheme.Gray ?? "",
    GradientColors: customTheme.ui?.gradient ?? customTheme.GradientColors
  };
  const rawMappings = {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: colors.Background,
      color: colors.Foreground
    },
    "hljs-keyword": {
      color: colors.AccentBlue
    },
    "hljs-literal": {
      color: colors.AccentBlue
    },
    "hljs-symbol": {
      color: colors.AccentBlue
    },
    "hljs-name": {
      color: colors.AccentBlue
    },
    "hljs-link": {
      color: colors.AccentBlue,
      textDecoration: "underline"
    },
    "hljs-built_in": {
      color: colors.AccentCyan
    },
    "hljs-type": {
      color: colors.AccentCyan
    },
    "hljs-number": {
      color: colors.AccentGreen
    },
    "hljs-class": {
      color: colors.AccentGreen
    },
    "hljs-string": {
      color: colors.AccentYellow
    },
    "hljs-meta-string": {
      color: colors.AccentYellow
    },
    "hljs-regexp": {
      color: colors.AccentRed
    },
    "hljs-template-tag": {
      color: colors.AccentRed
    },
    "hljs-subst": {
      color: colors.Foreground
    },
    "hljs-function": {
      color: colors.Foreground
    },
    "hljs-title": {
      color: colors.Foreground
    },
    "hljs-params": {
      color: colors.Foreground
    },
    "hljs-formula": {
      color: colors.Foreground
    },
    "hljs-comment": {
      color: colors.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: colors.Comment,
      fontStyle: "italic"
    },
    "hljs-doctag": {
      color: colors.Comment
    },
    "hljs-meta": {
      color: colors.Gray
    },
    "hljs-meta-keyword": {
      color: colors.Gray
    },
    "hljs-tag": {
      color: colors.Gray
    },
    "hljs-variable": {
      color: colors.AccentPurple
    },
    "hljs-template-variable": {
      color: colors.AccentPurple
    },
    "hljs-attr": {
      color: colors.LightBlue
    },
    "hljs-attribute": {
      color: colors.LightBlue
    },
    "hljs-builtin-name": {
      color: colors.LightBlue
    },
    "hljs-section": {
      color: colors.AccentYellow
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-bullet": {
      color: colors.AccentYellow
    },
    "hljs-selector-tag": {
      color: colors.AccentYellow
    },
    "hljs-selector-id": {
      color: colors.AccentYellow
    },
    "hljs-selector-class": {
      color: colors.AccentYellow
    },
    "hljs-selector-attr": {
      color: colors.AccentYellow
    },
    "hljs-selector-pseudo": {
      color: colors.AccentYellow
    },
    "hljs-addition": {
      backgroundColor: colors.AccentGreen,
      display: "inline-block",
      width: "100%"
    },
    "hljs-deletion": {
      backgroundColor: colors.AccentRed,
      display: "inline-block",
      width: "100%"
    }
  };
  const semanticColors = {
    text: {
      primary: customTheme.text?.primary ?? colors.Foreground,
      secondary: customTheme.text?.secondary ?? colors.Gray,
      link: customTheme.text?.link ?? colors.AccentBlue,
      accent: customTheme.text?.accent ?? colors.AccentPurple,
      code: customTheme.text?.code ?? colors.LightBlue
    },
    background: {
      primary: customTheme.background?.primary ?? colors.Background,
      diff: {
        added: customTheme.background?.diff?.added ?? colors.DiffAdded,
        removed: customTheme.background?.diff?.removed ?? colors.DiffRemoved
      }
    },
    border: {
      default: customTheme.border?.default ?? colors.Gray,
      focused: customTheme.border?.focused ?? colors.AccentBlue
    },
    ui: {
      comment: customTheme.ui?.comment ?? colors.Comment,
      symbol: customTheme.ui?.symbol ?? colors.Gray,
      gradient: customTheme.ui?.gradient ?? colors.GradientColors
    },
    status: {
      error: customTheme.status?.error ?? colors.AccentRed,
      success: customTheme.status?.success ?? colors.AccentGreen,
      warning: customTheme.status?.warning ?? colors.AccentYellow,
      errorDim: customTheme.status?.errorDim ?? colors.AccentRedDim,
      warningDim: customTheme.status?.warningDim ?? colors.AccentYellowDim
    }
  };
  return new Theme(
    customTheme.name,
    "custom",
    rawMappings,
    colors,
    semanticColors
  );
}
__name(createCustomTheme, "createCustomTheme");
function validateCustomTheme(customTheme) {
  if (customTheme.name && !isValidThemeName(customTheme.name)) {
    return {
      isValid: false,
      error: `Invalid theme name: ${customTheme.name}`
    };
  }
  return {
    isValid: true
  };
}
__name(validateCustomTheme, "validateCustomTheme");
function isValidThemeName(name) {
  return name.trim().length > 0 && name.trim().length <= 50;
}
__name(isValidThemeName, "isValidThemeName");

// packages/cli/src/ui/themes/default-light.ts
var DefaultLight = new Theme(
  "Default Light",
  "light",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: lightTheme.Background,
      color: lightTheme.Foreground
    },
    "hljs-comment": {
      color: lightTheme.Comment
    },
    "hljs-quote": {
      color: lightTheme.Comment
    },
    "hljs-variable": {
      color: lightTheme.Foreground
    },
    "hljs-keyword": {
      color: lightTheme.AccentBlue
    },
    "hljs-selector-tag": {
      color: lightTheme.AccentBlue
    },
    "hljs-built_in": {
      color: lightTheme.AccentBlue
    },
    "hljs-name": {
      color: lightTheme.AccentBlue
    },
    "hljs-tag": {
      color: lightTheme.AccentBlue
    },
    "hljs-string": {
      color: lightTheme.AccentRed
    },
    "hljs-title": {
      color: lightTheme.AccentRed
    },
    "hljs-section": {
      color: lightTheme.AccentRed
    },
    "hljs-attribute": {
      color: lightTheme.AccentRed
    },
    "hljs-literal": {
      color: lightTheme.AccentRed
    },
    "hljs-template-tag": {
      color: lightTheme.AccentRed
    },
    "hljs-template-variable": {
      color: lightTheme.AccentRed
    },
    "hljs-type": {
      color: lightTheme.AccentRed
    },
    "hljs-addition": {
      color: lightTheme.AccentGreen
    },
    "hljs-deletion": {
      color: lightTheme.AccentRed
    },
    "hljs-selector-attr": {
      color: lightTheme.AccentCyan
    },
    "hljs-selector-pseudo": {
      color: lightTheme.AccentCyan
    },
    "hljs-meta": {
      color: lightTheme.AccentCyan
    },
    "hljs-doctag": {
      color: lightTheme.Gray
    },
    "hljs-attr": {
      color: lightTheme.AccentRed
    },
    "hljs-symbol": {
      color: lightTheme.AccentCyan
    },
    "hljs-bullet": {
      color: lightTheme.AccentCyan
    },
    "hljs-link": {
      color: lightTheme.AccentCyan
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    }
  },
  lightTheme
);

// packages/cli/src/ui/themes/default.ts
init_esbuild_shims();
var DefaultDark = new Theme(
  "Default",
  "dark",
  {
    hljs: {
      display: "block",
      overflowX: "auto",
      padding: "0.5em",
      background: darkTheme.Background,
      color: darkTheme.Foreground
    },
    "hljs-keyword": {
      color: darkTheme.AccentBlue
    },
    "hljs-literal": {
      color: darkTheme.AccentBlue
    },
    "hljs-symbol": {
      color: darkTheme.AccentBlue
    },
    "hljs-name": {
      color: darkTheme.AccentBlue
    },
    "hljs-link": {
      color: darkTheme.AccentBlue,
      textDecoration: "underline"
    },
    "hljs-built_in": {
      color: darkTheme.AccentCyan
    },
    "hljs-type": {
      color: darkTheme.AccentCyan
    },
    "hljs-number": {
      color: darkTheme.AccentGreen
    },
    "hljs-class": {
      color: darkTheme.AccentGreen
    },
    "hljs-string": {
      color: darkTheme.AccentYellow
    },
    "hljs-meta-string": {
      color: darkTheme.AccentYellow
    },
    "hljs-regexp": {
      color: darkTheme.AccentRed
    },
    "hljs-template-tag": {
      color: darkTheme.AccentRed
    },
    "hljs-subst": {
      color: darkTheme.Foreground
    },
    "hljs-function": {
      color: darkTheme.Foreground
    },
    "hljs-title": {
      color: darkTheme.Foreground
    },
    "hljs-params": {
      color: darkTheme.Foreground
    },
    "hljs-formula": {
      color: darkTheme.Foreground
    },
    "hljs-comment": {
      color: darkTheme.Comment,
      fontStyle: "italic"
    },
    "hljs-quote": {
      color: darkTheme.Comment,
      fontStyle: "italic"
    },
    "hljs-doctag": {
      color: darkTheme.Comment
    },
    "hljs-meta": {
      color: darkTheme.Gray
    },
    "hljs-meta-keyword": {
      color: darkTheme.Gray
    },
    "hljs-tag": {
      color: darkTheme.Gray
    },
    "hljs-variable": {
      color: darkTheme.AccentPurple
    },
    "hljs-template-variable": {
      color: darkTheme.AccentPurple
    },
    "hljs-attr": {
      color: darkTheme.LightBlue
    },
    "hljs-attribute": {
      color: darkTheme.LightBlue
    },
    "hljs-builtin-name": {
      color: darkTheme.LightBlue
    },
    "hljs-section": {
      color: darkTheme.AccentYellow
    },
    "hljs-emphasis": {
      fontStyle: "italic"
    },
    "hljs-strong": {
      fontWeight: "bold"
    },
    "hljs-bullet": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-tag": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-id": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-class": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-attr": {
      color: darkTheme.AccentYellow
    },
    "hljs-selector-pseudo": {
      color: darkTheme.AccentYellow
    },
    "hljs-addition": {
      backgroundColor: "#144212",
      display: "inline-block",
      width: "100%"
    },
    "hljs-deletion": {
      backgroundColor: "#600",
      display: "inline-block",
      width: "100%"
    }
  },
  darkTheme
);

// packages/cli/src/config/modelProvidersScope.ts
init_esbuild_shims();
function hasOwnModelProviders(settingsObj) {
  if (!settingsObj || typeof settingsObj !== "object") {
    return false;
  }
  const obj = settingsObj;
  return Object.prototype.hasOwnProperty.call(obj, "modelProviders");
}
__name(hasOwnModelProviders, "hasOwnModelProviders");
function getModelProvidersOwnerScope(settings) {
  if (settings.isTrusted && hasOwnModelProviders(settings.workspace.settings)) {
    return "Workspace" /* Workspace */;
  }
  if (hasOwnModelProviders(settings.user.settings)) {
    return "User" /* User */;
  }
  return void 0;
}
__name(getModelProvidersOwnerScope, "getModelProvidersOwnerScope");
function getPersistScopeForModelSelection(settings) {
  return getModelProvidersOwnerScope(settings) ?? "User" /* User */;
}
__name(getPersistScopeForModelSelection, "getPersistScopeForModelSelection");

// packages/cli/src/config/settingsSchema.ts
init_esbuild_shims();
var TOGGLE_TYPES = /* @__PURE__ */ new Set([
  "boolean",
  "enum"
]);
var HOOK_DEFINITION_ITEMS = {
  type: "object",
  description: "A hook definition with an optional matcher and a list of hook configurations.",
  properties: {
    matcher: {
      type: "string",
      description: "An optional matcher pattern to filter when this hook definition applies."
    },
    sequential: {
      type: "boolean",
      description: "Whether the hooks should be executed sequentially instead of in parallel."
    },
    hooks: {
      type: "array",
      description: "The list of hook configurations to execute.",
      required: true,
      items: {
        type: "object",
        description: "A hook configuration entry that defines a hook to execute.",
        properties: {
          type: {
            type: "string",
            description: 'The type of hook. Note: "function" type is only available via SDK registration, not settings.json.',
            enum: ["command", "http"],
            required: true
          },
          command: {
            type: "string",
            description: 'The command to execute when the hook is triggered. Required for "command" type.'
          },
          url: {
            type: "string",
            description: 'The URL to send the POST request to. Required for "http" type.'
          },
          headers: {
            type: "object",
            description: "HTTP headers to include in the request. Supports env var interpolation ($VAR, ${VAR}).",
            additionalProperties: { type: "string" }
          },
          allowedEnvVars: {
            type: "array",
            description: "List of environment variables allowed for interpolation in headers and URL.",
            items: { type: "string" }
          },
          name: {
            type: "string",
            description: "An optional name for the hook."
          },
          description: {
            type: "string",
            description: "An optional description of what the hook does."
          },
          timeout: {
            type: "number",
            description: "Timeout in seconds for the hook execution."
          },
          env: {
            type: "object",
            description: "Environment variables to set when executing the hook command.",
            additionalProperties: { type: "string" }
          },
          async: {
            type: "boolean",
            description: 'Whether to execute the hook asynchronously (non-blocking, for "command" type only).'
          },
          once: {
            type: "boolean",
            description: 'Whether to execute the hook only once per session (for "http" type).'
          },
          statusMessage: {
            type: "string",
            description: "A message to display while the hook is executing."
          },
          shell: {
            type: "string",
            description: "The shell to use for command execution.",
            enum: ["bash", "powershell"]
          }
        }
      }
    }
  }
};
var SETTINGS_SCHEMA = {
  // Maintained for compatibility/criticality
  mcpServers: {
    type: "object",
    label: "MCP Servers",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for MCP servers.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  // Channels configuration (Telegram, Discord, etc.)
  channels: {
    type: "object",
    label: "Channels",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for messaging channels.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  // Model providers configuration grouped by authType
  modelProviders: {
    type: "object",
    label: "Model Providers",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Model providers configuration grouped by authType. Each authType contains an array of model configurations.",
    showInDialog: false,
    mergeStrategy: "replace" /* REPLACE */
  },
  plansDirectory: {
    type: "string",
    label: "Plans Directory",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Custom directory for approved Plan Mode files. Relative paths are resolved from the project root, and the resolved path must stay within the project root. Defaults to ~/.qwen/plans.",
    showInDialog: false
  },
  // Environment variables fallback
  env: {
    type: "object",
    label: "Environment Variables",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Environment variables to set as fallback defaults. These are loaded with the lowest priority: system environment variables > .env files > settings.json env field.",
    showInDialog: false,
    mergeStrategy: "shallow_merge" /* SHALLOW_MERGE */
  },
  proxy: {
    type: "string",
    label: "Proxy",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Proxy URL for CLI HTTP requests. Takes precedence over proxy environment variables when --proxy is not provided.",
    showInDialog: false
  },
  general: {
    type: "object",
    label: "General",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "General application settings.",
    showInDialog: false,
    properties: {
      preferredEditor: {
        type: "string",
        label: "Preferred Editor",
        category: "General",
        requiresRestart: false,
        default: void 0,
        description: "The preferred editor to open files in.",
        showInDialog: true
      },
      vimMode: {
        type: "boolean",
        label: "Vim Mode",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable Vim keybindings",
        showInDialog: true
      },
      voice: {
        type: "object",
        label: "Voice Dictation",
        category: "General",
        requiresRestart: false,
        default: {},
        description: "Voice dictation settings.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Voice Dictation",
            category: "General",
            requiresRestart: false,
            default: false,
            description: "Enable voice dictation in the prompt input.",
            showInDialog: false
          },
          mode: {
            type: "enum",
            label: "Voice Dictation Mode",
            category: "General",
            requiresRestart: false,
            default: "hold",
            description: 'How push-to-talk behaves: "hold" to talk while held, or "tap" to start and tap (or pause) to stop and submit.',
            showInDialog: false,
            options: [
              { value: "hold", label: "Hold to talk" },
              { value: "tap", label: "Tap to toggle" }
            ]
          },
          language: {
            type: "string",
            label: "Voice Dictation Language",
            category: "General",
            requiresRestart: false,
            default: "",
            description: 'Preferred spoken language for voice transcription (e.g. "english", "chinese"). Leave empty to auto-detect.',
            showInDialog: false
          }
        }
      },
      enableAutoUpdate: {
        type: "boolean",
        label: "Enable Auto Update",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Enable automatic update checks and installations on startup.",
        showInDialog: true
      },
      showSessionRecap: {
        type: "boolean",
        label: "Show Session Recap",
        category: "General",
        requiresRestart: false,
        // Off by default — an ambient background LLM call isn't something
        // users should be opted into silently, especially when `fastModel`
        // is unset and the call would land on the main coding model.
        // Manual `/recap` works regardless.
        default: false,
        description: 'Auto-show a one-line "where you left off" recap when returning to the terminal after being away. Off by default. Use /recap to trigger manually regardless of this setting.',
        showInDialog: true
      },
      sessionRecapAwayThresholdMinutes: {
        type: "number",
        label: "Session Recap Away Threshold (minutes)",
        category: "General",
        requiresRestart: false,
        default: 5,
        description: "How many minutes the terminal must be blurred before an auto-recap fires on the next focus-in. Matches Claude Code's default of 5 minutes; raise if you briefly alt-tab and do not want recaps to pile up.",
        showInDialog: true
      },
      cleanupPeriodDays: {
        type: "number",
        label: "Cleanup Period (days)",
        category: "General",
        // LoadedSettings._merged is cached without verified setValue→recompute
        // paths in all UI flows. Mark restart-required so users aren't
        // surprised when a mid-session edit doesn't take effect immediately.
        requiresRestart: true,
        default: 30,
        description: "Number of days to retain ~/.qwen/file-history/ session backups used by /rewind and background subagent transcripts under <projectDir>/subagents/. Data older than this is removed by a background housekeeping pass that runs at most once per day. Set to 0 for minimum retention (~1 hour) \u2014 protects sessions touched in the last hour, plus the currently active session.",
        showInDialog: true
      },
      gitCoAuthor: {
        type: "object",
        label: "Attribution",
        category: "General",
        requiresRestart: false,
        // Match `normalizeGitCoAuthor`'s runtime defaults so the IDE
        // schema publishes the same "enabled by default" hint users see
        // at runtime. The empty-object form here would silently lose
        // editor-surfaced defaults.
        default: { commit: true, pr: true },
        description: "Attribution added to git commits and pull requests created through Qwen Code.",
        showInDialog: false,
        // Pre-V4 settings stored this as a single boolean. The V3→V4
        // migration rewrites those on first launch, but the IDE schema
        // validator runs before that — accept the boolean shape so users
        // editing settings.json in VS Code don't see a spurious warning
        // until they run qwen once. Config.normalizeGitCoAuthor handles
        // the boolean at runtime.
        legacyTypes: ["boolean"],
        properties: {
          commit: {
            type: "boolean",
            label: "Attribution: commit",
            category: "General",
            requiresRestart: false,
            default: true,
            description: "Add a Co-authored-by trailer to git commit messages AND attach a per-file AI-attribution git note (`refs/notes/ai-attribution`) for commits made through Qwen Code. Disabling skips both.",
            showInDialog: true
          },
          pr: {
            type: "boolean",
            label: "Attribution: PR",
            category: "General",
            requiresRestart: false,
            default: true,
            description: "Append a Qwen Code attribution line to PR descriptions when running `gh pr create`.",
            showInDialog: true
          }
        }
      },
      debugKeystrokeLogging: {
        type: "boolean",
        label: "Debug Keystroke Logging",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable debug logging of keystrokes to the console.",
        showInDialog: false
      },
      language: {
        type: "enum",
        label: "Language: UI",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for the user interface. Use "auto" to detect from system settings. You can also use custom language codes (e.g., "es", "fr") by placing JS language files in ~/.qwen/locales/ (e.g., ~/.qwen/locales/es.js).',
        showInDialog: true,
        options: []
      },
      outputLanguage: {
        type: "string",
        label: "Language: Model",
        category: "General",
        requiresRestart: true,
        default: "auto",
        description: 'The language for LLM output. Use "auto" to detect from system settings, or set a specific language.',
        showInDialog: true
      },
      dynamicCommandTranslation: {
        type: "boolean",
        label: "Language: Dynamic Command Translation",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Enable AI translation for dynamic slash command descriptions. When disabled, dynamic commands use their original descriptions and do not trigger translation model calls.",
        showInDialog: true
      },
      terminalBell: {
        type: "boolean",
        label: "Terminal Bell Notification",
        category: "General",
        requiresRestart: false,
        default: true,
        description: "Play terminal bell sound when response completes or needs approval.",
        showInDialog: true
      },
      preventSystemSleep: {
        type: "boolean",
        label: "Prevent System Sleep While Running",
        category: "General",
        // Read once at startup via Config.preventSystemSleep (a readonly field
        // captured in loadCliConfig), so a runtime toggle only takes effect
        // after restart.
        requiresRestart: true,
        default: true,
        description: "Prevent the system from sleeping while Qwen Code is streaming a model response or executing tools. Idle prompt time and permission prompts do not inhibit sleep.",
        showInDialog: true
      },
      chatRecording: {
        type: "boolean",
        label: "Chat Recording",
        category: "General",
        requiresRestart: true,
        default: true,
        description: "Enable saving chat history to disk. Disabling this will also prevent --continue and --resume from working.",
        showInDialog: false
      },
      defaultFileEncoding: {
        type: "enum",
        label: "Default File Encoding",
        category: "General",
        requiresRestart: false,
        default: "utf-8",
        description: 'Default encoding for new files. Use "utf-8" (default) for UTF-8 without BOM, or "utf-8-bom" for UTF-8 with BOM. Only change this if your project specifically requires BOM.',
        showInDialog: false,
        options: [
          { value: "utf-8", label: "UTF-8 (without BOM)" },
          { value: "utf-8-bom", label: "UTF-8 with BOM" }
        ]
      }
    }
  },
  output: {
    type: "object",
    label: "Output",
    category: "General",
    requiresRestart: false,
    default: {},
    description: "Settings for the CLI output.",
    showInDialog: false,
    properties: {
      format: {
        type: "enum",
        label: "Output Format",
        category: "General",
        requiresRestart: false,
        default: "text",
        description: "The format of the CLI output.",
        showInDialog: false,
        options: [
          { value: "text", label: "Text" },
          { value: "json", label: "JSON" }
        ]
      },
      showTimestamps: {
        type: "boolean",
        label: "Show Timestamps",
        category: "General",
        requiresRestart: false,
        default: false,
        description: "Show [HH:MM:SS] timestamp before each assistant response.",
        showInDialog: true
      }
    }
  },
  dualOutput: {
    type: "object",
    label: "Dual Output",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Dual-output sidecar mode: emit structured JSON events to a second channel while the TUI renders normally on stdout. See docs/users/features/dual-output.md. CLI flags take precedence over these settings.",
    showInDialog: false,
    properties: {
      jsonFile: {
        type: "string",
        label: "JSON Event File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for structured JSON event output. Equivalent to --json-file. Ignored if --json-fd or --json-file is also set.",
        showInDialog: false
      },
      inputFile: {
        type: "string",
        label: "Remote Input File",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "File path for remote input commands (JSONL). Equivalent to --input-file. Ignored if --input-file is also set.",
        showInDialog: false
      }
    }
  },
  ui: {
    type: "object",
    label: "UI",
    category: "UI",
    requiresRestart: false,
    default: {},
    description: "User interface settings.",
    showInDialog: false,
    properties: {
      theme: {
        type: "string",
        label: "Theme",
        category: "UI",
        requiresRestart: false,
        default: "Qwen Dark",
        description: "The color theme for the UI.",
        showInDialog: true
      },
      autoModeAcknowledged: {
        type: "boolean",
        label: "Auto Mode Acknowledged",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "True once the user has seen the first-time information message about the AUTO approval mode. Set automatically; not intended for manual configuration.",
        showInDialog: false
      },
      statusLine: {
        type: "object",
        label: "Status Line",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: 'Status line display configuration. Use `type: "preset"` with built-in item ids, or `type: "command"` with a shell command. Optional command `refreshInterval` (seconds, >= 1) re-runs the command on a timer so external data stays fresh. Set `respectUserColors: true` to preserve ANSI color codes in command output instead of applying dim/theme styling. Set `hideContextIndicator: true` to hide the built-in context usage indicator in the footer right section.',
        showInDialog: false
      },
      customThemes: {
        type: "object",
        label: "Custom Themes",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "Custom theme definitions.",
        showInDialog: false
      },
      hideBuiltinWorktreeIndicator: {
        type: "boolean",
        label: "Hide Built-in Worktree Indicator",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "When true, the built-in `\u2387 worktree-<branch> (<slug>)` line in the Footer is hidden. The worktree state is still surfaced to custom statusline scripts via the stdin payload (`worktree.{name, path, branch, original_cwd, original_branch}`). Keep at the default `false` unless your custom statusline renders the worktree itself \u2014 otherwise an active worktree silently has no UI affordance.",
        showInDialog: false
      },
      hideWindowTitle: {
        type: "boolean",
        label: "Hide Window Title",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Hide the window title bar",
        showInDialog: false
      },
      disableWorkflowKeywordTrigger: {
        type: "boolean",
        label: "Disable Workflow Keyword Trigger",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "When true, mentioning the word `workflow` in a prompt no longer softly steers the turn toward the Workflow tool (and the Footer `workflow active` indicator is suppressed). Only applies when workflows are enabled.",
        showInDialog: true
      },
      showStatusInTitle: {
        type: "boolean",
        label: "Show Status in Title",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show Qwen Code session name and status in the terminal window title",
        showInDialog: true
      },
      hideTips: {
        type: "boolean",
        label: "Hide Tips",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide helpful tips in the UI",
        showInDialog: true
      },
      history: {
        type: "object",
        label: "History",
        category: "UI",
        requiresRestart: false,
        default: {},
        description: "History display settings.",
        showInDialog: false,
        properties: {
          collapseOnResume: {
            type: "boolean",
            label: "Collapse On Resume",
            category: "UI",
            requiresRestart: false,
            default: false,
            description: "Whether to collapse history by default when resuming a session.",
            showInDialog: false
          }
        }
      },
      showLineNumbers: {
        type: "boolean",
        label: "Show Line Numbers in Code",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show line numbers in the code output.",
        showInDialog: true
      },
      renderMode: {
        type: "enum",
        label: "Markdown Render Mode",
        category: "UI",
        requiresRestart: false,
        default: "render",
        description: 'Default Markdown display mode. Use "render" for rich visual previews, or "raw" to show source-oriented Markdown by default. Toggle during a session with Alt/Option+M; on macOS the terminal must send Option as Meta.',
        showInDialog: true,
        options: [
          { value: "render", label: "Render visual previews" },
          { value: "raw", label: "Show raw source" }
        ]
      },
      showCitations: {
        type: "boolean",
        label: "Show Citations",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Show citations for generated text in the chat.",
        showInDialog: false
      },
      customWittyPhrases: {
        type: "array",
        label: "Custom Witty Phrases",
        category: "UI",
        requiresRestart: false,
        default: [],
        description: "Custom witty phrases to display during loading.",
        showInDialog: false
      },
      showResponseTokensPerSecond: {
        type: "boolean",
        label: "Show Response Tokens Per Second",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Show a live tokens/sec estimate next to the response token counter while the model is streaming. Takes effect in the next session.",
        showInDialog: true
      },
      enableWelcomeBack: {
        type: "boolean",
        label: "Show Welcome Back Dialog",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: 'Show welcome back dialog when returning to a project with conversation history. Choosing "Start new chat session" suppresses the dialog for that project until the project summary changes.',
        showInDialog: true
      },
      enableUserFeedback: {
        type: "boolean",
        label: "Enable User Feedback",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show optional feedback dialog after conversations to help improve Qwen performance.",
        showInDialog: true
      },
      enableFollowupSuggestions: {
        type: "boolean",
        label: "Enable Follow-up Suggestions",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Show context-aware follow-up suggestions after task completion. Press Tab, Right Arrow, or Enter to accept into the input buffer.",
        showInDialog: true
      },
      enableCacheSharing: {
        type: "boolean",
        label: "Enable Cache Sharing for Suggestions",
        category: "UI",
        requiresRestart: false,
        default: true,
        description: "Use cache-aware forked queries for suggestion generation. Reduces cost on providers that support prefix caching (experimental).",
        showInDialog: false
      },
      enableSpeculation: {
        type: "boolean",
        label: "Enable Speculative Execution",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Speculatively execute accepted suggestions before submission. Results appear instantly when you accept (experimental).",
        showInDialog: false
      },
      accessibility: {
        type: "object",
        label: "Accessibility",
        category: "UI",
        requiresRestart: true,
        default: {},
        description: "Accessibility settings.",
        showInDialog: false,
        properties: {
          enableLoadingPhrases: {
            type: "boolean",
            label: "Enable Loading Phrases",
            category: "UI",
            requiresRestart: true,
            default: true,
            description: "Enable loading phrases (disable for accessibility)",
            showInDialog: true
          },
          screenReader: {
            type: "boolean",
            label: "Screen Reader Mode",
            category: "UI",
            requiresRestart: true,
            default: void 0,
            description: "Render output in plain-text to be more screen reader accessible",
            showInDialog: false
          }
        }
      },
      feedbackLastShownTimestamp: {
        type: "number",
        label: "Feedback Last Shown Timestamp",
        category: "UI",
        requiresRestart: false,
        default: 0,
        description: "The last time the feedback dialog was shown.",
        showInDialog: false
      },
      compactMode: {
        type: "boolean",
        label: "Compact Mode",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide tool output and thinking for a cleaner view (toggle with Ctrl+O).",
        showInDialog: true
      },
      compactInline: {
        type: "boolean",
        label: "Compact Inline",
        category: "UI",
        requiresRestart: true,
        default: false,
        description: "Compact tool display within each group instead of merging across groups. Requires compactMode to be enabled.",
        showInDialog: true
      },
      useTerminalBuffer: {
        type: "boolean",
        label: "Virtualized History (reduces flicker on long sessions)",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Render conversation history in an in-app scrollable viewport instead of the terminal scrollback buffer. Recommended if you see flicker, scroll-storm, or interface freeze on long sessions, after Ctrl+O, after Ctrl+E / Ctrl+F (expand), after window resize, or when alt-tabbing back. Scroll with Shift+\u2191/\u2193 (line), PgUp/PgDn (page), Ctrl+Home/End (top/bottom), or the mouse wheel. Does NOT use the host terminal scrollback while enabled; for native text selection, hold Shift (or Option on macOS) while dragging.",
        showInDialog: true
      },
      shellOutputMaxLines: {
        type: "number",
        label: "Shell Output Max Lines",
        category: "UI",
        requiresRestart: false,
        default: 5,
        description: "Max number of shell output lines shown inline. Set to 0 to disable the cap and show full output. The hidden line count is still surfaced via the `+N lines` indicator.",
        showInDialog: true
      },
      hideBanner: {
        type: "boolean",
        label: "Hide Banner",
        category: "UI",
        requiresRestart: false,
        default: false,
        description: "Hide the startup ASCII banner and info panel.",
        showInDialog: true
      },
      customBannerTitle: {
        type: "string",
        label: "Custom Banner Title",
        category: "UI",
        requiresRestart: false,
        default: "",
        description: 'Replace the default ">_ Qwen Code" title shown in the banner info panel. The version suffix is always appended.',
        showInDialog: false
      },
      customBannerSubtitle: {
        type: "string",
        label: "Custom Banner Subtitle",
        category: "UI",
        requiresRestart: false,
        default: "",
        description: "Optional subtitle line rendered between the banner title and the auth/model line. When unset, the info panel keeps its blank spacer row.",
        showInDialog: false
      },
      customAsciiArt: {
        type: "object",
        label: "Custom ASCII Art",
        category: "UI",
        requiresRestart: false,
        default: void 0,
        description: 'Replace the default QWEN ASCII art. Accepts an inline string, {"path": "..."}, or {"small": ..., "large": ...} for width-aware selection.',
        showInDialog: false,
        // The runtime accepts three shapes (inline string, {path}, or
        // {small,large} where each tier is itself string-or-{path}). The
        // SettingDefinition `type: 'object'` keeps the in-app dialog out of
        // the way (we don't want a multi-line ASCII editor in the TUI), but
        // the JSON Schema needs a real union so VS Code stops flagging the
        // documented bare-string form.
        // The `oneOf` here uses three *mutually exclusive* branches rather
        // than one permissive object branch, so VS Code rejects nonsense
        // like `{ path, small, large }` (which the runtime would also
        // reject — see `normalizeTiers` in `customBanner.ts`).
        jsonSchemaOverride: {
          oneOf: [
            { type: "string" },
            // Bare `{path}` — no tier keys allowed.
            {
              type: "object",
              properties: { path: { type: "string" } },
              required: ["path"],
              additionalProperties: false
            },
            // Width-aware `{small?, large?}` — `path` not allowed at this
            // level; each tier is itself string-or-`{path}`.
            {
              type: "object",
              properties: {
                small: {
                  oneOf: [
                    { type: "string" },
                    {
                      type: "object",
                      properties: { path: { type: "string" } },
                      required: ["path"],
                      additionalProperties: false
                    }
                  ]
                },
                large: {
                  oneOf: [
                    { type: "string" },
                    {
                      type: "object",
                      properties: { path: { type: "string" } },
                      required: ["path"],
                      additionalProperties: false
                    }
                  ]
                }
              },
              additionalProperties: false
            }
          ]
        }
      }
    }
  },
  ide: {
    type: "object",
    label: "IDE",
    category: "IDE",
    requiresRestart: true,
    default: {},
    description: "IDE integration settings.",
    showInDialog: false,
    properties: {
      enabled: {
        type: "boolean",
        label: "Auto-connect to IDE",
        category: "IDE",
        requiresRestart: true,
        default: false,
        description: "Enable IDE integration mode",
        showInDialog: true
      },
      hasSeenNudge: {
        type: "boolean",
        label: "Has Seen IDE Integration Nudge",
        category: "IDE",
        requiresRestart: false,
        default: false,
        description: "Whether the user has seen the IDE integration nudge.",
        showInDialog: false
      }
    }
  },
  privacy: {
    type: "object",
    label: "Privacy",
    category: "Privacy",
    requiresRestart: true,
    default: {},
    description: "Privacy-related settings.",
    showInDialog: false,
    properties: {
      usageStatisticsEnabled: {
        type: "boolean",
        label: "Enable Usage Statistics",
        category: "Privacy",
        requiresRestart: true,
        default: true,
        description: "Enable collection of usage statistics",
        showInDialog: true
      }
    }
  },
  telemetry: {
    type: "object",
    label: "Telemetry",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "Telemetry configuration.",
    showInDialog: false,
    jsonSchemaOverride: {
      type: "object",
      properties: {
        includeSensitiveSpanAttributes: {
          description: "When enabled, user prompts, system prompts, tool inputs/outputs, and model responses are written to native OTel span attributes in addition to the log-to-span bridge. Warning: this may expose sensitive data (file contents, shell commands, conversation history) to your OTLP backend.",
          type: "boolean",
          default: false
        },
        resourceAttributes: {
          description: "Static resource attributes attached to every span/log/metric the SDK exports (OTLP or file outfile \u2014 they share the same Resource). Merged with the OTEL_RESOURCE_ATTRIBUTES env var; settings win on key conflict. Reserved keys (service.version, session.id) are dropped with a warning.",
          type: "object",
          additionalProperties: { type: "string" },
          default: {}
        },
        metrics: {
          description: "Per-signal cardinality controls for exported metrics.",
          type: "object",
          additionalProperties: false,
          properties: {
            includeSessionId: {
              description: "Include session.id on every metric data point. WARNING: each CLI session creates a new value, causing unbounded metric time-series fan-out at the backend. Only enable for short-term debugging \u2014 spans and logs still carry session.id.",
              type: "boolean",
              default: false
            }
          }
        }
      },
      additionalProperties: true
    }
  },
  outboundCorrelation: {
    type: "object",
    label: "Outbound Correlation",
    category: "Advanced",
    requiresRestart: true,
    default: void 0,
    description: "SECURITY-RELEVANT. Controls what client-side correlation data qwen-code writes into outbound LLM API requests (DashScope, OpenAI, Anthropic, etc.) \u2014 separate from `telemetry.*` which governs data flow into the operator's OWN OTLP collector. All values default to off. Opt in only when the LLM provider also reports into your OTel collector for cross-process trace stitching (e.g. ARMS Tracing + DashScope).",
    showInDialog: false,
    jsonSchemaOverride: {
      type: "object",
      properties: {
        propagateTraceContext: {
          description: "Requires `telemetry.enabled: true`. Inject W3C `traceparent` on outbound `fetch` requests (LLM SDK calls, MCP StreamableHTTP, WebFetch, ...) AND as a `TRACEPARENT` environment variable in shell child processes (Bash tool, hooks, monitor). When enabled, any existing `TRACEPARENT` in the parent environment is overwritten with qwen-code's own trace context. Default: false \u2014 trace context stays internal to the operator's OTLP collector. Set true when you want cross-process trace stitching with an OTel-aware LLM provider (e.g. ARMS+DashScope) or need shell scripts / CLI tools to participate in distributed tracing.",
          type: "boolean",
          default: false
        }
      },
      additionalProperties: false
    }
  },
  fastModel: {
    type: "string",
    label: "Fast Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Model used for generating prompt suggestions and speculative execution. Leave empty to use the main model. A smaller/faster model (e.g., qwen3-coder-flash) reduces latency and cost.",
    showInDialog: true
  },
  voiceModel: {
    type: "string",
    label: "Voice Model",
    category: "Model",
    requiresRestart: false,
    default: "",
    description: "Model used for voice transcription. Set with /model --voice. Leave empty to keep voice dictation disabled until a voice model is selected.",
    showInDialog: false
  },
  model: {
    type: "object",
    label: "Model",
    category: "Model",
    requiresRestart: false,
    default: {},
    description: "Settings related to the generative model.",
    showInDialog: false,
    properties: {
      name: {
        type: "string",
        label: "Model",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The model to use for conversations.",
        showInDialog: false
      },
      baseUrl: {
        type: "string",
        label: "Model Base URL",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Base URL paired with model.name; disambiguates which provider to use when multiple modelProviders entries share the same model id.",
        showInDialog: false
      },
      maxSessionTurns: {
        type: "number",
        label: "Max Session Turns",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: "Maximum number of user/model/tool turns to keep in a session. -1 means unlimited.",
        showInDialog: false
      },
      maxWallTimeSeconds: {
        type: "number",
        label: "Max Wall-Clock Time (seconds)",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: "Run-level wall-clock budget for headless / unattended runs, in seconds. -1 means unlimited; otherwise must be in [1, ~2,147,483] (sub-second values and values above ~24 days are rejected as typos). Overridable per-invocation via --max-wall-time (which also accepts duration suffixes like 5m, 1.5h).",
        showInDialog: false
      },
      maxToolCalls: {
        type: "number",
        label: "Max Tool Calls",
        category: "Model",
        requiresRestart: false,
        default: -1,
        description: 'Cumulative tool-call budget for a run (counts every executed tool, success or failure; structured_output under --json-schema is exempt). -1 means unlimited; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos. Overridable via --max-tool-calls.',
        showInDialog: false
      },
      chatCompression: {
        type: "object",
        label: "Chat Compression",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Chat compression settings.",
        showInDialog: false
      },
      sessionTokenLimit: {
        type: "number",
        label: "Session Token Limit",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "The maximum number of tokens allowed in a session.",
        showInDialog: false
      },
      skipNextSpeakerCheck: {
        type: "boolean",
        label: "Skip Next Speaker Check",
        category: "Model",
        requiresRestart: false,
        default: true,
        description: "Skip the next speaker check.",
        showInDialog: false
      },
      skipWorkflowUsageWarning: {
        type: "boolean",
        label: "Skip Workflow Usage Warning",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Suppress the one-time Workflow tool usage banner that describes the QWEN_CODE_MAX_TOKENS_PER_WORKFLOW env knob. The banner fires at most once per session regardless of this setting.",
        showInDialog: false
      },
      skipLoopDetection: {
        type: "boolean",
        label: "Skip Loop Detection",
        category: "Model",
        requiresRestart: false,
        default: true,
        description: "Skip the opt-in streaming loop-detection heuristics (content/thought repetition, read-file and action stagnation, global-duplicate and alternating tool-call patterns). Defaults to true to avoid false-positive interruptions; set to false to re-enable them as an unattended-run guardrail. A minimal always-on guard (consecutive identical tool calls plus a per-turn tool-call cap) still runs regardless of this setting.",
        showInDialog: false
      },
      skipStartupContext: {
        type: "boolean",
        label: "Skip Startup Context",
        category: "Model",
        requiresRestart: true,
        default: false,
        description: "Avoid sending the workspace startup context at the beginning of each session.",
        showInDialog: false
      },
      enableOpenAILogging: {
        type: "boolean",
        label: "Enable OpenAI Logging",
        category: "Model",
        requiresRestart: false,
        default: false,
        description: "Enable OpenAI logging.",
        showInDialog: false
      },
      openAILoggingDir: {
        type: "string",
        label: "OpenAI Logging Directory",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Custom directory path for OpenAI API logs. If not specified, defaults to logs/openai in the current working directory.",
        showInDialog: false
      },
      generationConfig: {
        type: "object",
        label: "Generation Configuration",
        category: "Model",
        requiresRestart: false,
        default: void 0,
        description: "Generation configuration settings.",
        showInDialog: false,
        properties: {
          timeout: {
            type: "number",
            label: "Timeout",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Request timeout in milliseconds.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          maxRetries: {
            type: "number",
            label: "Max Retries",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of retries for failed requests.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          enableCacheControl: {
            type: "boolean",
            label: "Enable Cache Control",
            category: "Generation Configuration",
            requiresRestart: false,
            default: true,
            description: "Enable cache control for DashScope providers.",
            parentKey: "generationConfig",
            showInDialog: false
          },
          splitToolMedia: {
            type: "boolean",
            label: "Split Tool Result Media",
            category: "Generation Configuration",
            requiresRestart: false,
            default: true,
            description: 'When true, media (images / audio / video / files) returned by tool calls \u2014 including the built-in read_file and MCP tools \u2014 is split into a follow-up user message instead of being embedded in the `role: "tool"` message. The OpenAI Chat Completions spec only permits text on tool messages, so strict OpenAI-compatible servers (e.g., doubao / new-api / LM Studio) silently drop or reject embedded media and the model never sees an image read via read_file (QwenLM/qwen-code#4876, #3616). Default true is spec-compliant and safe for permissive providers; set false only to restore the legacy embed-in-tool-message behavior.',
            parentKey: "generationConfig",
            showInDialog: false
          },
          toolResultContentFormat: {
            type: "enum",
            label: "Tool Result Content Format",
            category: "Generation Configuration",
            requiresRestart: false,
            default: "parts",
            description: 'Controls how text-only tool results are serialized in OpenAI-compatible requests. Use "parts" for the default content-part array shape. Use "string" only for legacy OpenAI-compatible runtimes whose tool templates ignore text content parts (for example older GLM-5.1 vLLM/SGLang templates; QwenLM/qwen-code#3361). Tool-returned media is still handled by splitToolMedia.',
            parentKey: "generationConfig",
            showInDialog: false,
            options: [
              { value: "parts", label: "Content Parts (Default)" },
              { value: "string", label: "String" }
            ]
          },
          schemaCompliance: {
            type: "enum",
            label: "Tool Schema Compliance",
            category: "Generation Configuration",
            requiresRestart: false,
            default: "auto",
            description: 'The compliance mode for tool schemas sent to the model. Use "openapi_30" for strict OpenAPI 3.0 compatibility (e.g., for Gemini).',
            parentKey: "generationConfig",
            showInDialog: false,
            options: [
              { value: "auto", label: "Auto (Default)" },
              { value: "openapi_30", label: "OpenAPI 3.0 Strict" }
            ]
          },
          contextWindowSize: {
            type: "number",
            label: "Context Window Size",
            category: "Generation Configuration",
            requiresRestart: false,
            default: void 0,
            description: "Overrides the default context window size for the selected model. Use this setting when a provider's effective context limit differs from Qwen Code's default. This value defines the model's assumed maximum context capacity, not a per-request token limit.",
            parentKey: "generationConfig",
            showInDialog: false
          }
        }
      }
    }
  },
  modelPricing: {
    type: "object",
    label: "Model Pricing",
    category: "Model",
    requiresRestart: false,
    default: void 0,
    description: 'Optional per-model pricing for cost estimation in /stats model. Example: {"qwen3-coder": {"inputPerMillionTokens": 0.30, "outputPerMillionTokens": 1.20}}',
    showInDialog: false
  },
  context: {
    type: "object",
    label: "Context",
    category: "Context",
    requiresRestart: false,
    default: {},
    description: "Settings for managing context provided to the model.",
    showInDialog: false,
    properties: {
      fileName: {
        type: "object",
        label: "Context File Name",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The name of the context file or files.",
        showInDialog: false,
        jsonSchemaOverride: {
          anyOf: [
            { type: "string" },
            { type: "array", items: { type: "string" } }
          ]
        }
      },
      importFormat: {
        type: "enum",
        label: "Memory Import Format",
        category: "Context",
        requiresRestart: false,
        default: void 0,
        description: "The format to use when importing memory.",
        showInDialog: false,
        options: [
          { value: "tree", label: "Tree" },
          { value: "flat", label: "Flat" }
        ]
      },
      includeDirectories: {
        type: "array",
        label: "Include Directories",
        category: "Context",
        requiresRestart: false,
        default: [],
        description: "Additional directories to include in the workspace context. Missing directories will be skipped with a warning.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      loadFromIncludeDirectories: {
        type: "boolean",
        label: "Load Memory From Include Directories",
        category: "Context",
        requiresRestart: false,
        default: false,
        description: "Whether to load memory files from include directories.",
        showInDialog: false
      },
      clearContextOnIdle: {
        type: "object",
        label: "Clear Context On Idle",
        category: "Context",
        requiresRestart: false,
        default: {},
        description: "Settings for clearing stale or oversized tool result context. Use -1 to disable a threshold.",
        showInDialog: false,
        properties: {
          toolResultsThresholdMinutes: {
            type: "number",
            label: "Tool Results Idle Threshold (minutes)",
            category: "Context",
            requiresRestart: false,
            default: 60,
            description: "Minutes of inactivity before clearing old tool result content. Use -1 to disable.",
            showInDialog: false
          },
          toolResultsNumToKeep: {
            type: "number",
            label: "Tool Results Number To Keep",
            category: "Context",
            requiresRestart: false,
            default: 5,
            description: "Number of most-recent compactable tool results to preserve when clearing. Floor at 1.",
            showInDialog: false
          },
          toolResultsTotalCharsThreshold: {
            type: "number",
            label: "Tool Results Total Chars Threshold",
            category: "Context",
            requiresRestart: false,
            default: DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,
            description: "Total compactable tool result output characters allowed in history before clearing oldest results. Use -1 to disable. This is a soft threshold: protected recent tool results may keep the total above it.",
            showInDialog: false
          }
        }
      },
      fileFiltering: {
        type: "object",
        label: "File Filtering",
        category: "Context",
        requiresRestart: true,
        default: {},
        description: "Settings for git-aware file filtering.",
        showInDialog: false,
        properties: {
          respectGitIgnore: {
            type: "boolean",
            label: "Respect .gitignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .gitignore files when searching",
            showInDialog: true
          },
          respectQwenIgnore: {
            type: "boolean",
            label: "Respect .qwenignore",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Respect .qwenignore and configured custom ignore files when searching",
            showInDialog: true
          },
          customIgnoreFiles: {
            type: "array",
            label: "Custom Ignore Files",
            category: "Context",
            requiresRestart: true,
            default: [...DEFAULT_QWEN_CUSTOM_IGNORE_FILE_NAMES],
            description: "Project-root-relative ignore files to use instead of the defaults (`.agentignore`, `.aiignore`) when respectQwenIgnore is enabled. .qwenignore is always included when respectQwenIgnore is enabled.",
            showInDialog: false,
            items: { type: "string" }
          },
          enableRecursiveFileSearch: {
            type: "boolean",
            label: "Enable Recursive File Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable recursive file search functionality",
            showInDialog: false
          },
          enableFuzzySearch: {
            type: "boolean",
            label: "Enable Fuzzy Search",
            category: "Context",
            requiresRestart: true,
            default: true,
            description: "Enable fuzzy search when searching for files.",
            showInDialog: true
          }
        }
      }
    }
  },
  memory: {
    type: "object",
    label: "Memory",
    category: "Memory",
    requiresRestart: false,
    default: {},
    description: "Settings for managed auto-memory.",
    showInDialog: false,
    properties: {
      enableManagedAutoMemory: {
        type: "boolean",
        label: "Enable Managed Auto-Memory",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable background extraction of memories from conversations.",
        showInDialog: false
      },
      enableManagedAutoDream: {
        type: "boolean",
        label: "Enable Managed Auto-Dream",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable automatic consolidation (dream) of collected memories.",
        showInDialog: false
      },
      enableAutoSkill: {
        type: "boolean",
        label: "Enable Auto Skill",
        category: "Memory",
        requiresRestart: false,
        default: true,
        description: "Enable background review for reusable project skills after tool-heavy sessions.",
        showInDialog: false
      }
    }
  },
  slashCommands: {
    type: "object",
    label: "Slash Commands",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Configuration for slash commands exposed by the CLI. Useful for locking down the command surface in multi-tenant or enterprise deployments.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Slash Commands",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: 'Slash command names to hide and refuse to execute. Matched case-insensitively against the final command name (for extension commands this is the disambiguated form, e.g. "myext.deploy"). Merged as a union across settings scopes, so workspace settings can add to but not remove entries defined in system/user settings.',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  skills: {
    type: "object",
    label: "Skills",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Configuration for skills (SKILL.md-based capabilities) exposed to the model.",
    showInDialog: false,
    properties: {
      disabled: {
        type: "array",
        label: "Disabled Skills",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Skill names to hide. Matched case-insensitively against the skill name. Hidden skills do not appear in <available_skills> or as /<name> slash commands. UNION-merged across systemDefaults/user/workspace/system scopes \u2014 workspace cannot remove entries defined in higher scopes.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      }
    }
  },
  permissions: {
    type: "object",
    label: "Permissions",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Permission rules controlling tool usage. Rules are evaluated in priority order: deny > ask > allow.",
    showInDialog: false,
    properties: {
      allow: {
        type: "array",
        label: "Allow Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are auto-approved without confirmation. Examples: "ShellTool", "Bash(git *)", "ReadFileTool".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      ask: {
        type: "array",
        label: "Ask Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tools or commands that always require user confirmation. Takes precedence over allow rules.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      deny: {
        type: "array",
        label: "Deny Rules",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: 'Tools or commands that are always blocked. Highest priority rule. Examples: "ShellTool", "Bash(rm -rf *)".',
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      autoMode: {
        type: "object",
        label: "Auto Mode",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Settings consumed by the AUTO approval mode classifier.",
        showInDialog: false,
        properties: {
          classifier: {
            type: "object",
            label: "Auto Mode Classifier",
            category: "Tools",
            requiresRestart: true,
            default: {},
            description: "Runtime controls for the AUTO approval mode classifier.",
            showInDialog: false,
            properties: {
              timeouts: {
                type: "object",
                label: "Auto Mode Classifier Timeouts",
                category: "Tools",
                requiresRestart: true,
                default: {},
                description: "Timeouts for the two AUTO classifier stages, in milliseconds.",
                showInDialog: false,
                properties: {
                  stage1Ms: {
                    type: "number",
                    label: "Auto Mode Stage 1 Timeout",
                    category: "Tools",
                    requiresRestart: true,
                    default: void 0,
                    description: "Timeout in milliseconds for the fast stage-1 AUTO classifier.",
                    showInDialog: false
                  },
                  stage2Ms: {
                    type: "number",
                    label: "Auto Mode Stage 2 Timeout",
                    category: "Tools",
                    requiresRestart: true,
                    default: void 0,
                    description: "Timeout in milliseconds for the stage-2 AUTO classifier review.",
                    showInDialog: false
                  }
                }
              },
              thinking: {
                type: "object",
                label: "Auto Mode Classifier Thinking",
                category: "Tools",
                requiresRestart: true,
                default: {},
                description: "Provider/API-level thinking controls for the AUTO classifier.",
                showInDialog: false,
                properties: {
                  stage2Enabled: {
                    type: "boolean",
                    label: "Auto Mode Stage 2 Thinking",
                    category: "Tools",
                    requiresRestart: true,
                    default: false,
                    description: "Whether stage 2 may use provider/API-level thinking. Stage 1 always keeps thinking disabled.",
                    showInDialog: false
                  }
                }
              }
            }
          },
          hints: {
            type: "object",
            label: "Classifier Hints",
            category: "Tools",
            requiresRestart: true,
            default: {},
            description: "Natural-language hints injected into the classifier system prompt.",
            showInDialog: false,
            properties: {
              allow: {
                type: "array",
                label: "Auto Mode Allow Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of actions AUTO mode should allow.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              softDeny: {
                type: "array",
                label: "Auto Mode Soft-Deny Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of destructive / irreversible actions AUTO mode should block unless the user explicitly authorised that exact action and scope.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              hardDeny: {
                type: "array",
                label: "Auto Mode Hard-Deny Hints",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Natural-language descriptions of security-boundary actions the AUTO classifier must block even when an autoMode allow hint or recent user request would normally authorise them. Does not override permissions.allow; use permissions.deny for deterministic hard permission rules.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              },
              deny: {
                type: "array",
                label: "Auto Mode Deny Hints (legacy)",
                category: "Tools",
                requiresRestart: true,
                default: void 0,
                description: "Deprecated alias for `softDeny`. Entries here are merged into the SOFT BLOCK user section so existing settings keep working; new configurations should use `softDeny` or `hardDeny` instead.",
                showInDialog: false,
                mergeStrategy: "union" /* UNION */
              }
            }
          },
          environment: {
            type: "array",
            label: "Auto Mode Environment",
            category: "Tools",
            requiresRestart: true,
            default: void 0,
            description: "Environment / context lines injected into the classifier system prompt.",
            showInDialog: false,
            mergeStrategy: "union" /* UNION */
          }
        }
      }
    }
  },
  tools: {
    type: "object",
    label: "Tools",
    category: "Tools",
    requiresRestart: true,
    default: {},
    description: "Settings for built-in and custom tools.",
    showInDialog: false,
    properties: {
      sandbox: {
        type: "object",
        label: "Sandbox",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox execution environment (can be a boolean or a path string).",
        showInDialog: false,
        jsonSchemaOverride: {
          anyOf: [{ type: "boolean" }, { type: "string" }]
        }
      },
      sandboxImage: {
        type: "string",
        label: "Sandbox Image",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Sandbox image URI used by Docker/Podman when --sandbox-image and QWEN_SANDBOX_IMAGE are not set.",
        showInDialog: false
      },
      toolSearch: {
        type: "object",
        label: "Tool Search",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Settings for the ToolSearch discovery mechanism.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Enable ToolSearch",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "When enabled, MCP tools are loaded on-demand via ToolSearch to reduce prompt size. Disable this for models that rely on prefix-based KV caching (e.g. DeepSeek) to keep the prompt prefix stable and maximize cache hit rates.",
            showInDialog: true
          }
        }
      },
      shell: {
        type: "object",
        label: "Shell",
        category: "Tools",
        requiresRestart: false,
        default: {},
        description: "Settings for shell execution.",
        showInDialog: false,
        properties: {
          enableInteractiveShell: {
            type: "boolean",
            label: "Interactive Shell (PTY)",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "Use node-pty for an interactive shell experience. Falls back to child_process if PTY is unavailable.",
            showInDialog: true
          },
          pager: {
            type: "string",
            label: "Pager",
            category: "Tools",
            requiresRestart: false,
            default: "cat",
            description: "The pager command to use for shell output. Defaults to `cat`.",
            showInDialog: false
          },
          showColor: {
            type: "boolean",
            label: "Show Color",
            category: "Tools",
            requiresRestart: false,
            default: false,
            description: "Show color in shell output.",
            showInDialog: false
          }
        }
      },
      // Legacy tool permission fields – kept for backward compatibility.
      // Use permissions.{allow,ask,deny} instead.
      core: {
        type: "array",
        label: "Core Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allowed Tools (deprecated)",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.allow instead.",
        showInDialog: false
      },
      exclude: {
        type: "array",
        label: "Exclude Tools (deprecated)",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Deprecated. Use permissions.deny instead.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      disabled: {
        type: "array",
        label: "Disabled Tools",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Tool names hidden from the registry. Differs from permissions.deny: disabled tools are not registered at all, so they never appear in /tools and cannot be discovered by the model. Managed by the daemon mutation route POST /workspace/tools/:name/enable.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      approvalMode: {
        type: "enum",
        label: "Tool Approval Mode",
        category: "Tools",
        requiresRestart: false,
        default: "default" /* DEFAULT */,
        description: "Approval mode for tool usage. Controls how tools are approved before execution.",
        showInDialog: true,
        options: [
          { value: "plan" /* PLAN */, label: "Plan" },
          { value: "default" /* DEFAULT */, label: "Ask permissions" },
          { value: "auto-edit" /* AUTO_EDIT */, label: "Auto Edit" },
          { value: "auto" /* AUTO */, label: "Auto" },
          { value: "yolo" /* YOLO */, label: "YOLO" }
        ]
      },
      autoAccept: {
        type: "boolean",
        label: "Auto Accept",
        category: "Tools",
        requiresRestart: false,
        default: false,
        description: "Automatically accept and execute tool calls that are considered safe (e.g., read-only operations) without explicit user confirmation.",
        showInDialog: false
      },
      discoveryCommand: {
        type: "string",
        label: "Tool Discovery Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool discovery.",
        showInDialog: false
      },
      callCommand: {
        type: "string",
        label: "Tool Call Command",
        category: "Tools",
        requiresRestart: true,
        default: void 0,
        description: "Command to run for tool calls.",
        showInDialog: false
      },
      useRipgrep: {
        type: "boolean",
        label: "Use Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: "Use ripgrep for file content search instead of the fallback implementation. Provides faster search performance.",
        showInDialog: false
      },
      useBuiltinRipgrep: {
        type: "boolean",
        label: "Use Builtin Ripgrep",
        category: "Tools",
        requiresRestart: false,
        default: true,
        description: 'Use the bundled ripgrep binary. When set to false, the system-level "rg" command will be used instead. This setting is only effective when useRipgrep is true.',
        showInDialog: false
      },
      truncateToolOutputThreshold: {
        type: "number",
        label: "Tool Output Truncation Threshold",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,
        description: "Truncate tool output if it is larger than this many characters. Set to -1 to disable.",
        showInDialog: false
      },
      truncateToolOutputLines: {
        type: "number",
        label: "Tool Output Truncation Lines",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,
        description: "The number of lines to keep when truncating tool output.",
        showInDialog: false
      },
      toolOutputBatchBudget: {
        type: "number",
        label: "Tool Output Batch Budget",
        category: "General",
        requiresRestart: true,
        default: DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,
        description: "Per-message budget (characters) for the combined output of one batch of tool calls; the largest results are offloaded to disk when exceeded. Set to -1 to disable.",
        showInDialog: false
      },
      computerUse: {
        type: "object",
        label: "Computer Use",
        category: "Tools",
        requiresRestart: true,
        default: {},
        description: "Cross-platform desktop automation via the cua-driver native driver (trycua/cua). On first invocation a pinned, signed + notarized binary (~20MB) is downloaded into ~/.qwen/computer-use/ and the user is walked through macOS Accessibility / Screen Recording permissions if needed. Exposes cua-driver's full tool surface (click, type_text, scroll, drag, press_key, get_window_state, page, launch_app, and more).",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Enable Computer Use",
            category: "Tools",
            requiresRestart: true,
            default: true,
            description: "When enabled (default), the cua-driver computer_use__* tools are registered as deferred built-ins.",
            showInDialog: true
          },
          maxImageDimension: {
            type: "number",
            label: "Max Screenshot Dimension",
            category: "Tools",
            requiresRestart: true,
            default: -1,
            description: "Longest-edge pixel cap applied to cua-driver screenshots (via set_config's max_image_dimension). -1 (default) keeps cua-driver's built-in default (1568); 0 disables resizing (full resolution); a positive value caps the longest edge. Lower caps cut vision-token cost at the expense of fine detail. Overridable via the QWEN_COMPUTER_USE_MAX_IMAGE_DIMENSION env var.",
            showInDialog: false
          }
        }
      }
    }
  },
  policy: {
    type: "object",
    label: "Daemon Policy",
    category: "Daemon",
    requiresRestart: true,
    default: {},
    description: "Daemon multi-client coordination policies. Tool-level allow/deny rules live under `permissions`; this section is for runtime mediation behavior between concurrent HTTP clients sharing one `qwen serve` daemon.",
    showInDialog: false,
    properties: {
      permissionStrategy: {
        type: "enum",
        label: "Permission Mediation Policy",
        category: "Daemon",
        requiresRestart: true,
        default: "first-responder",
        description: 'How permission requests resolve when multiple clients are attached. `first-responder` (default) = any client decides, first wins. `designated` = only the prompt originator decides; falls back to first-responder if originator is anonymous. NOTE: client identity comes from self-declared X-Qwen-Client-Id with no proof-of-possession (pair-token identity is not implemented yet), so any client observing originatorClientId on SSE frames can register with the same id and impersonate the originator. `consensus` = N-of-M voters must agree. Default N=floor(M/2)+1, which means UNANIMITY for M=2 (quorum=2, both must agree) and supermajority for larger even M (M=4 \u2192 quorum=3; M=6 \u2192 quorum=4). For M=2 specifically, split votes resolve only via permissionTimeoutMs. `local-only` = only loopback clients can RESOLVE; remote clients can still ABORT a pending permission via the cancel sentinel ({outcome:"cancelled"}) \u2014 cancel stays cross-policy for consistency. Strict-cancel-too deployments need a dedicated loopback-bound daemon. Requires daemon restart \u2014 read once at boot.',
        showInDialog: true,
        options: [
          { value: "first-responder", label: "First Responder" },
          { value: "designated", label: "Designated Originator" },
          { value: "consensus", label: "Consensus Quorum" },
          { value: "local-only", label: "Local Only" }
        ]
      },
      consensusQuorum: {
        type: "number",
        label: "Consensus Quorum Override",
        category: "Daemon",
        requiresRestart: true,
        default: void 0,
        description: "Optional fixed quorum size for consensus policy. Capped at M (count of registered voters at request issue time) to prevent unreachable quorum. Unset = floor(M/2)+1. Requires daemon restart \u2014 read once at boot.",
        showInDialog: false,
        // run-qwen-serve.ts validates `Number.isInteger(n) && n >= 1` and
        // refuses to boot otherwise. Override the generated schema so IDE
        // (VSCode, JetBrains via JSON Schema) flags `0`, `-1`, `1.5`
        // BEFORE the user restarts the daemon. The bare `type:'number'`
        // mapping accepts all of these.
        jsonSchemaOverride: {
          type: "integer",
          minimum: 1,
          description: "Optional fixed quorum size for consensus policy. Capped at M (count of registered voters at request issue time) to prevent unreachable quorum. Unset = floor(M/2)+1. Requires daemon restart \u2014 read once at boot."
        }
      }
    }
  },
  mcp: {
    type: "object",
    label: "MCP",
    category: "MCP",
    requiresRestart: true,
    default: {},
    description: "Settings for Model Context Protocol (MCP) servers.",
    showInDialog: false,
    properties: {
      serverCommand: {
        type: "string",
        label: "MCP Server Command",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "Command to start an MCP server.",
        showInDialog: false
      },
      allowed: {
        type: "array",
        label: "Allow MCP Servers",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "A list of MCP servers to allow.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      },
      excluded: {
        type: "array",
        label: "Exclude MCP Servers",
        category: "MCP",
        requiresRestart: true,
        default: void 0,
        description: "A list of MCP servers to exclude.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */
      }
    }
  },
  security: {
    type: "object",
    label: "Security",
    category: "Security",
    requiresRestart: true,
    default: {},
    description: "Security-related settings.",
    showInDialog: false,
    properties: {
      folderTrust: {
        type: "object",
        label: "Folder Trust",
        category: "Security",
        requiresRestart: false,
        default: {},
        description: "Settings for folder trust.",
        showInDialog: false,
        properties: {
          enabled: {
            type: "boolean",
            label: "Folder Trust",
            category: "Security",
            requiresRestart: true,
            default: false,
            description: "Setting to track whether Folder trust is enabled.",
            showInDialog: false
          }
        }
      },
      auth: {
        type: "object",
        label: "Authentication",
        category: "Security",
        requiresRestart: true,
        default: {},
        description: "Authentication settings.",
        showInDialog: false,
        properties: {
          selectedType: {
            type: "string",
            label: "Selected Auth Type",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "The currently selected authentication type.",
            showInDialog: false
          },
          enforcedType: {
            type: "string",
            label: "Enforced Auth Type",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "The required auth type. If this does not match the selected auth type, the user will be prompted to re-authenticate.",
            showInDialog: false
          },
          useExternal: {
            type: "boolean",
            label: "Use External Auth",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Whether to use an external authentication flow.",
            showInDialog: false
          },
          apiKey: {
            type: "string",
            label: "API Key",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "API key for OpenAI compatible authentication.",
            showInDialog: false
          },
          baseUrl: {
            type: "string",
            label: "Base URL",
            category: "Security",
            requiresRestart: true,
            default: void 0,
            description: "Base URL for OpenAI compatible API.",
            showInDialog: false
          }
        }
      },
      allowedHttpHookUrls: {
        type: "array",
        label: "Allowed HTTP Hook URLs",
        category: "Security",
        requiresRestart: false,
        default: [],
        description: "Whitelist of URL patterns for HTTP hooks. Supports * wildcard. If empty, all URLs are allowed (subject to SSRF protection).",
        showInDialog: false,
        items: {
          type: "string",
          description: "URL pattern (supports * wildcard)"
        }
      }
    }
  },
  advanced: {
    type: "object",
    label: "Advanced",
    category: "Advanced",
    requiresRestart: true,
    default: {},
    description: "Advanced settings for power users.",
    showInDialog: false,
    properties: {
      autoConfigureMemory: {
        type: "boolean",
        label: "Auto Configure Max Old Space Size",
        category: "Advanced",
        requiresRestart: true,
        default: false,
        description: "Automatically configure Node.js memory limits",
        showInDialog: false
      },
      dnsResolutionOrder: {
        type: "enum",
        label: "DNS Resolution Order",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "The DNS resolution order.",
        showInDialog: false,
        options: [
          { value: "ipv4first", label: "IPv4 First" },
          { value: "verbatim", label: "Verbatim" }
        ]
      },
      excludedEnvVars: {
        type: "array",
        label: "Excluded Project Environment Variables",
        category: "Advanced",
        requiresRestart: false,
        default: ["DEBUG", "DEBUG_MODE"],
        description: "Environment variables to exclude from project context.",
        showInDialog: false,
        mergeStrategy: "union" /* UNION */
      },
      bugCommand: {
        type: "object",
        label: "Bug Command",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Configuration for the bug report command.",
        showInDialog: false
      },
      runtimeOutputDir: {
        type: "string",
        label: "Runtime Output Directory",
        category: "Advanced",
        requiresRestart: true,
        default: void 0,
        description: "Custom directory for runtime output (temp files, debug logs, session data, todos, etc.). Config files remain at ~/.qwen (or QWEN_HOME if set). Env var QWEN_RUNTIME_DIR takes priority.",
        showInDialog: false
      }
    }
  },
  agents: {
    type: "object",
    label: "Agents",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Settings for multi-agent collaboration features (Arena, Team, Swarm).",
    showInDialog: false,
    properties: {
      displayMode: {
        type: "enum",
        label: "Display Mode",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: 'Display mode for multi-agent sessions. Currently only "in-process" is supported.',
        showInDialog: false,
        options: [
          { value: "in-process", label: "In-process" }
          // { value: 'tmux', label: 'tmux' },
          // { value: 'iterm2', label: 'iTerm2' },
        ]
      },
      arena: {
        type: "object",
        label: "Arena",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Arena (multi-model competitive execution).",
        showInDialog: false,
        properties: {
          worktreeBaseDir: {
            type: "string",
            label: "Worktree Base Directory",
            category: "Advanced",
            requiresRestart: true,
            default: void 0,
            description: "Custom base directory for Arena worktrees. Defaults to ~/.qwen/arena.",
            showInDialog: false
          },
          preserveArtifacts: {
            type: "boolean",
            label: "Preserve Arena Artifacts",
            category: "Advanced",
            requiresRestart: false,
            default: false,
            description: "When enabled, Arena worktrees and session state files are preserved after the session ends or the main agent exits.",
            showInDialog: true
          },
          maxRoundsPerAgent: {
            type: "number",
            label: "Max Rounds Per Agent",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Maximum number of rounds (turns) each agent can execute. No limit if unset.",
            showInDialog: false
          },
          timeoutSeconds: {
            type: "number",
            label: "Timeout (seconds)",
            category: "Advanced",
            requiresRestart: false,
            default: void 0,
            description: "Total timeout in seconds for the Arena session. No limit if unset.",
            showInDialog: false
          }
        }
      },
      team: {
        type: "object",
        label: "Team",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Team (role-based collaborative execution). Reserved for future use.",
        showInDialog: false
      },
      swarm: {
        type: "object",
        label: "Swarm",
        category: "Advanced",
        requiresRestart: false,
        default: {},
        description: "Settings for Agent Swarm (parallel sub-agent execution). Reserved for future use.",
        showInDialog: false
      }
    }
  },
  disableAllHooks: {
    type: "boolean",
    label: "Disable All Hooks",
    category: "Advanced",
    requiresRestart: true,
    // Future enhancement: consider supporting mid-session toggle for better UX
    default: false,
    description: "Temporarily disable all hooks without deleting configurations. Default is false (hooks enabled).",
    showInDialog: false
  },
  stopHookBlockingCap: {
    type: "number",
    label: "Stop Hook Blocking Cap",
    category: "Advanced",
    requiresRestart: true,
    default: DEFAULT_STOP_HOOK_BLOCK_CAP,
    description: "Maximum consecutive blocking Stop/SubagentStop hook decisions before Qwen Code overrides the hook loop and ends the turn. Can be overridden by QWEN_CODE_STOP_HOOK_BLOCK_CAP.",
    // This is an advanced safety valve for runaway hook loops, not a common
    // interactive preference.
    showInDialog: false
  },
  hooks: {
    type: "object",
    label: "Hooks",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: "Hook event configurations for extending CLI behavior at various lifecycle points.",
    showInDialog: false,
    properties: {
      UserPromptSubmit: {
        type: "array",
        label: "Before Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before agent processing. Can modify prompts or inject context.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      UserPromptExpansion: {
        type: "array",
        label: "Prompt Expansion Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a slash command expands into a prompt.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Stop: {
        type: "array",
        label: "After Agent Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after agent processing. Can post-process responses or log interactions.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      Notification: {
        type: "array",
        label: "Notification Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when notifications are sent.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreToolUse: {
        type: "array",
        label: "Pre Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUse: {
        type: "array",
        label: "Post Tool Use Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute after successful tool execution.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolUseFailure: {
        type: "array",
        label: "Post Tool Use Failure Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when tool execution fails. ",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PostToolBatch: {
        type: "array",
        label: "Post Tool Batch Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute once after all tool calls in a batch resolve.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionStart: {
        type: "array",
        label: "Session Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a new session starts or resumes.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SessionEnd: {
        type: "array",
        label: "Session End Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a session ends.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PreCompact: {
        type: "array",
        label: "Pre Compact Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute before conversation compaction.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStart: {
        type: "array",
        label: "Subagent Start Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a subagent (Task tool call) is started.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      SubagentStop: {
        type: "array",
        label: "Subagent Stop Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute right before a subagent (Task tool call) concludes its response.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      },
      PermissionRequest: {
        type: "array",
        label: "Permission Request Hooks",
        category: "Advanced",
        requiresRestart: false,
        default: [],
        description: "Hooks that execute when a permission dialog is displayed.",
        showInDialog: false,
        mergeStrategy: "concat" /* CONCAT */,
        items: HOOK_DEFINITION_ITEMS
      }
    }
  },
  experimental: {
    type: "object",
    label: "Experimental",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Settings to enable experimental features.",
    showInDialog: false,
    properties: {
      cron: {
        type: "boolean",
        label: "Enable Cron/Loop Tools",
        category: "Experimental",
        requiresRestart: true,
        default: true,
        description: "Enable in-session cron/loop tools. When enabled, the model can create recurring prompts using cron_create, cron_list, and cron_delete tools. Can be disabled via QWEN_CODE_DISABLE_CRON=1 environment variable.",
        showInDialog: true
      },
      agentTeam: {
        type: "boolean",
        label: "Enable Agent Team",
        category: "Experimental",
        requiresRestart: true,
        default: false,
        description: "Enable agent team collaboration tools (experimental). When enabled, the model can create agent teams and coordinate work using team_create, team_delete, send_message, task_create, task_update, and task_list tools. Can also be enabled via QWEN_CODE_ENABLE_AGENT_TEAM=1 environment variable.",
        showInDialog: true
      },
      artifact: {
        type: "boolean",
        label: "Enable Artifacts",
        category: "Experimental",
        requiresRestart: true,
        default: false,
        description: "Enable the Artifact tool (experimental). When enabled, the model can publish a self-contained HTML page as an interactive Artifact and open it in the browser. Interactive, non-SDK sessions only. Can also be enabled via QWEN_CODE_ENABLE_ARTIFACT=1, or hard-disabled via QWEN_CODE_DISABLE_ARTIFACT=1.",
        showInDialog: true
      },
      emitToolUseSummaries: {
        type: "boolean",
        label: "Tool Use Summaries",
        category: "Experimental",
        requiresRestart: false,
        default: true,
        description: "Generate a short LLM-based label after each tool batch completes. In compact mode the label replaces the generic `Tool \xD7 N` header; in full mode it appears as a dim `\u25CF <label>` line below the tool group. Requires a fast model to be configured; runs in parallel with the next API call so latency is hidden. Currently affects interactive CLI rendering only \u2014 SDK / non-interactive emission of the `tool_use_summary` message is not yet wired (the message factory is exported for a follow-up PR). Can be overridden with QWEN_CODE_EMIT_TOOL_USE_SUMMARIES=0 or =1.",
        showInDialog: true
      }
    }
  },
  artifact: {
    type: "object",
    label: "Artifacts",
    category: "Experimental",
    requiresRestart: true,
    default: {},
    description: "Configuration for the experimental Artifact tool (enable it via experimental.artifact). Selects the publish backend and, for the host backend, the upload command and shareable URL template.",
    showInDialog: false,
    properties: {
      autoOpen: {
        type: "boolean",
        label: "Auto-open Artifacts",
        category: "Experimental",
        requiresRestart: true,
        default: true,
        description: "Open published artifacts in the browser automatically. Set to false to publish without launching a browser. QWEN_ARTIFACT_NO_AUTO_OPEN=1 overrides this setting.",
        showInDialog: false
      },
      publisher: {
        type: "enum",
        label: "Artifact Publisher",
        category: "Experimental",
        requiresRestart: true,
        default: "local",
        description: "Where artifacts are published: 'local' (a file:// page on disk, the default), 'host' (upload via artifact.host.uploadCommand and return a shareable link), or 'oss' (native Aliyun OSS upload).",
        showInDialog: false,
        options: [
          { value: "local", label: "Local (file://)" },
          { value: "host", label: "Host (shareable link)" },
          { value: "oss", label: "Aliyun OSS" }
        ]
      },
      host: {
        type: "object",
        label: "Artifact Host",
        category: "Experimental",
        requiresRestart: true,
        default: {},
        description: 'Host-backend config, used when artifact.publisher is "host".',
        showInDialog: false,
        properties: {
          uploadCommand: {
            type: "string",
            label: "Upload Command",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Command that uploads the artifact, run with execFile (no shell). {file} = local HTML path, {key} = remote object key. e.g. "aws s3 cp {file} s3://bucket/{key} --content-type text/html".',
            showInDialog: false
          },
          urlTemplate: {
            type: "string",
            label: "URL Template",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Shareable URL template; {key} is substituted. e.g. "https://bucket.example.com/{key}".',
            showInDialog: false
          },
          keyPrefix: {
            type: "string",
            label: "Key Prefix",
            category: "Experimental",
            requiresRestart: true,
            default: "artifacts",
            description: 'Remote key prefix; the object key is "{prefix}/{id}/index.html".',
            showInDialog: false
          }
        }
      },
      oss: {
        type: "object",
        label: "Artifact OSS",
        category: "Experimental",
        requiresRestart: true,
        default: {},
        description: 'Native Aliyun OSS backend, used when artifact.publisher is "oss". Credentials are read from OSS_ACCESS_KEY_ID / OSS_ACCESS_KEY_SECRET (or ALIBABA_CLOUD_*), never from settings.',
        showInDialog: false,
        properties: {
          bucket: {
            type: "string",
            label: "OSS Bucket",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: "OSS bucket name.",
            showInDialog: false
          },
          endpoint: {
            type: "string",
            label: "OSS Endpoint",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'OSS endpoint host, e.g. "oss-cn-hangzhou.aliyuncs.com".',
            showInDialog: false
          },
          keyPrefix: {
            type: "string",
            label: "Key Prefix",
            category: "Experimental",
            requiresRestart: true,
            default: "artifacts",
            description: 'Remote key prefix; the object key is "{prefix}/{id}/index.html".',
            showInDialog: false
          },
          acl: {
            type: "string",
            label: "Object ACL",
            category: "Experimental",
            requiresRestart: true,
            default: "public-read",
            description: 'Object ACL applied on upload. "public-read" (default) makes the link shareable.',
            showInDialog: false
          },
          publicBaseUrl: {
            type: "string",
            label: "Public Base URL",
            category: "Experimental",
            requiresRestart: true,
            default: "",
            description: 'Optional CDN / custom-domain base for the returned URL. Upload still goes through endpoint. e.g. "https://cdn.example.com".',
            showInDialog: false
          }
        }
      }
    }
  },
  worktree: {
    type: "object",
    label: "Worktree",
    category: "Advanced",
    requiresRestart: false,
    default: {},
    description: 'Configuration for general-purpose git worktrees created by the CLI (the `enter_worktree` tool, the `agent isolation: "worktree"` parameter, and the startup `--worktree` flag). Does NOT affect Agent Arena worktrees \u2014 see `agents.arena.worktreeBaseDir` for those.',
    showInDialog: false,
    properties: {
      symlinkDirectories: {
        type: "array",
        label: "Symlink Directories Into Worktrees",
        category: "Advanced",
        requiresRestart: false,
        default: void 0,
        description: "Directories under the main repository to symlink into every general-purpose worktree on creation. Useful for sharing large opt-in dirs like `node_modules` so the model can run tests / builds inside the worktree without a fresh install. Paths must be relative to the repo root; absolute paths, anything containing `..`, and any path inside `.git` or `.qwen` (the CLI-managed metadata tree, which contains the worktrees directory itself) are rejected. Missing source dirs and existing destination paths are silently skipped (no overwrite, no failure).",
        showInDialog: false
      }
    }
  }
};
function getSettingsSchema() {
  const schema = SETTINGS_SCHEMA;
  if (schema["general"]?.properties?.["language"]) {
    schema["general"].properties["language"].options = getLanguageSettingsOptions();
  }
  return SETTINGS_SCHEMA;
}
__name(getSettingsSchema, "getSettingsSchema");

// packages/cli/src/utils/envVarResolver.ts
init_esbuild_shims();
function resolveEnvVarsInString(value, customEnv) {
  const envVarRegex = /\$(?:(\w+)|{([^}]+)})/g;
  return value.replace(envVarRegex, (match, varName1, varName2) => {
    const varName = varName1 || varName2;
    if (customEnv && typeof customEnv[varName] === "string") {
      return customEnv[varName];
    }
    if (process && process.env && typeof process.env[varName] === "string") {
      return process.env[varName];
    }
    return match;
  });
}
__name(resolveEnvVarsInString, "resolveEnvVarsInString");
function resolveEnvVarsInObject(obj, customEnv) {
  return resolveEnvVarsInObjectInternal(obj, /* @__PURE__ */ new WeakSet(), customEnv);
}
__name(resolveEnvVarsInObject, "resolveEnvVarsInObject");
function resolveEnvVarsInObjectInternal(obj, visited, customEnv) {
  if (obj === null || obj === void 0 || typeof obj === "boolean" || typeof obj === "number") {
    return obj;
  }
  if (typeof obj === "string") {
    return resolveEnvVarsInString(obj, customEnv);
  }
  if (Array.isArray(obj)) {
    if (visited.has(obj)) {
      return [...obj];
    }
    visited.add(obj);
    const result = obj.map(
      (item) => resolveEnvVarsInObjectInternal(item, visited, customEnv)
    );
    visited.delete(obj);
    return result;
  }
  if (typeof obj === "object") {
    if (visited.has(obj)) {
      return { ...obj };
    }
    visited.add(obj);
    const newObj = { ...obj };
    for (const key in newObj) {
      if (Object.prototype.hasOwnProperty.call(newObj, key)) {
        newObj[key] = resolveEnvVarsInObjectInternal(
          newObj[key],
          visited,
          customEnv
        );
      }
    }
    visited.delete(obj);
    return newObj;
  }
  return obj;
}
__name(resolveEnvVarsInObjectInternal, "resolveEnvVarsInObjectInternal");

// packages/cli/src/utils/settingsUtils.ts
init_esbuild_shims();
import * as fs5 from "node:fs";
function flattenSchema(schema, prefix = "") {
  let result = {};
  for (const key in schema) {
    const newKey = prefix ? `${prefix}.${key}` : key;
    const definition = schema[key];
    result[newKey] = { ...definition, key: newKey };
    if (definition.properties) {
      result = { ...result, ...flattenSchema(definition.properties, newKey) };
    }
  }
  return result;
}
__name(flattenSchema, "flattenSchema");
var _FLATTENED_SCHEMA;
function getFlattenedSchema() {
  return _FLATTENED_SCHEMA ?? (_FLATTENED_SCHEMA = flattenSchema(getSettingsSchema()));
}
__name(getFlattenedSchema, "getFlattenedSchema");
function getSettingDefinition(key) {
  return getFlattenedSchema()[key];
}
__name(getSettingDefinition, "getSettingDefinition");
function requiresRestart(key) {
  return getFlattenedSchema()[key]?.requiresRestart ?? false;
}
__name(requiresRestart, "requiresRestart");
function getDefaultValue(key) {
  return getFlattenedSchema()[key]?.default;
}
__name(getDefaultValue, "getDefaultValue");
function getNestedValue(obj, path9) {
  const [first, ...rest] = path9;
  if (!first || !(first in obj)) {
    return void 0;
  }
  const value = obj[first];
  if (rest.length === 0) {
    return value;
  }
  if (value && typeof value === "object" && value !== null) {
    return getNestedValue(value, rest);
  }
  return void 0;
}
__name(getNestedValue, "getNestedValue");
function getNestedProperty(obj, path9) {
  return getNestedValue(obj, path9.split("."));
}
__name(getNestedProperty, "getNestedProperty");
function getEffectiveValue(key, settings, mergedSettings) {
  const definition = getSettingDefinition(key);
  if (!definition) {
    return void 0;
  }
  const path9 = key.split(".");
  let value = getNestedValue(settings, path9);
  if (value !== void 0) {
    return value;
  }
  value = getNestedValue(mergedSettings, path9);
  if (value !== void 0) {
    return value;
  }
  return definition.default;
}
__name(getEffectiveValue, "getEffectiveValue");
var SETTINGS_DIALOG_ORDER = [
  // Workflow Control - most impactful setting
  "tools.approvalMode",
  // Localization - users often set this first
  "general.language",
  "general.outputLanguage",
  // Theme
  "ui.theme",
  // Editor/Shell Experience
  "general.vimMode",
  "tools.shell.enableInteractiveShell",
  // Display Preferences
  "general.preferredEditor",
  "ide.enabled",
  "ui.showLineNumbers",
  "ui.hideTips",
  "general.terminalBell",
  "ui.enableWelcomeBack",
  // Git Behavior
  "general.gitCoAuthor.commit",
  "general.gitCoAuthor.pr",
  // File Filtering
  "context.fileFiltering.respectGitIgnore",
  "context.fileFiltering.respectQwenIgnore",
  // System Settings - rarely changed
  "general.disableAutoUpdate",
  // Privacy
  "privacy.usageStatisticsEnabled"
];
function getDialogSettingKeys() {
  const dialogSettings = Object.values(getFlattenedSchema()).filter((definition) => definition.showInDialog === true).map((definition) => definition.key);
  return dialogSettings.sort((a, b) => {
    const indexA = SETTINGS_DIALOG_ORDER.indexOf(a);
    const indexB = SETTINGS_DIALOG_ORDER.indexOf(b);
    if (indexA !== -1 && indexB !== -1) {
      return indexA - indexB;
    }
    if (indexA !== -1) return -1;
    if (indexB !== -1) return 1;
    return 0;
  });
}
__name(getDialogSettingKeys, "getDialogSettingKeys");
function settingExistsInScope(key, scopeSettings) {
  const path9 = key.split(".");
  const value = getNestedValue(scopeSettings, path9);
  return value !== void 0;
}
__name(settingExistsInScope, "settingExistsInScope");
function pathHasUnsafeSegment(keys) {
  for (const key of keys) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      return true;
    }
  }
  return false;
}
__name(pathHasUnsafeSegment, "pathHasUnsafeSegment");
function setNestedPropertyForce(obj, path9, value) {
  const keys = path9.split(".");
  if (pathHasUnsafeSegment(keys)) return;
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (!current[key] || typeof current[key] !== "object") {
      current[key] = {};
    }
    current = current[key];
  }
  current[lastKey] = value;
}
__name(setNestedPropertyForce, "setNestedPropertyForce");
function setNestedPropertySafe(obj, path9, value) {
  const keys = path9.split(".");
  if (pathHasUnsafeSegment(keys)) return;
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    if (current[key] === void 0) {
      current[key] = {};
    }
    const next = current[key];
    if (typeof next === "object" && next !== null) {
      current = next;
    } else {
      return;
    }
  }
  current[lastKey] = value;
}
__name(setNestedPropertySafe, "setNestedPropertySafe");
function deleteNestedPropertySafe(obj, path9) {
  const keys = path9.split(".");
  const lastKey = keys.pop();
  if (!lastKey) return;
  let current = obj;
  for (const key of keys) {
    const next = current[key];
    if (typeof next !== "object" || next === null) {
      return;
    }
    current = next;
  }
  delete current[lastKey];
}
__name(deleteNestedPropertySafe, "deleteNestedPropertySafe");
function setPendingSettingValue(key, value, pendingSettings) {
  const newSettings = JSON.parse(JSON.stringify(pendingSettings));
  setNestedPropertyForce(newSettings, key, value);
  return newSettings;
}
__name(setPendingSettingValue, "setPendingSettingValue");
function setPendingSettingValueAny(key, value, pendingSettings) {
  const newSettings = structuredClone(pendingSettings);
  setNestedPropertyForce(newSettings, key, value);
  return newSettings;
}
__name(setPendingSettingValueAny, "setPendingSettingValueAny");
function getRestartRequiredFromModified(modifiedSettings) {
  return Array.from(modifiedSettings).filter((key) => requiresRestart(key));
}
__name(getRestartRequiredFromModified, "getRestartRequiredFromModified");
function saveModifiedSettings(modifiedSettings, pendingSettings, loadedSettings, scope) {
  modifiedSettings.forEach((settingKey) => {
    const path9 = settingKey.split(".");
    const value = getNestedValue(
      pendingSettings,
      path9
    );
    const existsInOriginalFile = settingExistsInScope(
      settingKey,
      loadedSettings.forScope(scope).settings
    );
    if (value === void 0) {
      if (existsInOriginalFile) {
        loadedSettings.setValue(scope, settingKey, void 0);
      }
      return;
    }
    const isDefaultValue2 = value === getDefaultValue(settingKey);
    if (existsInOriginalFile || !isDefaultValue2) {
      loadedSettings.setValue(scope, settingKey, value);
    }
  });
}
__name(saveModifiedSettings, "saveModifiedSettings");
function getDisplayValue(key, settings, _mergedSettings, modifiedSettings, pendingSettings) {
  const definition = getSettingDefinition(key);
  let value;
  if (pendingSettings && settingExistsInScope(key, pendingSettings)) {
    value = getEffectiveValue(key, pendingSettings, {});
  } else if (settingExistsInScope(key, settings)) {
    value = getEffectiveValue(key, settings, {});
  } else {
    value = getDefaultValue(key);
  }
  let valueString = String(value);
  if (key === "general.outputLanguage" && isAutoLanguage(value)) {
    valueString = t("Auto (detect from system)");
  } else if (definition?.type === "enum" && definition.options) {
    const option = definition.options?.find((option2) => option2.value === value);
    if (option?.label) {
      valueString = t(option.label) || option.label;
    } else {
      valueString = `${value}`;
    }
  }
  const defaultValue = getDefaultValue(key);
  const isChangedFromDefault = value !== defaultValue;
  const isInModifiedSettings = modifiedSettings.has(key);
  if (settingExistsInScope(key, settings) || isInModifiedSettings) {
    return `${valueString}*`;
  }
  if (isChangedFromDefault || isInModifiedSettings) {
    return `${valueString}*`;
  }
  return valueString;
}
__name(getDisplayValue, "getDisplayValue");
function isDefaultValue(key, settings) {
  return !settingExistsInScope(key, settings);
}
__name(isDefaultValue, "isDefaultValue");
function backupSettingsFile(filePath) {
  try {
    if (fs5.existsSync(filePath)) {
      const backupPath = `${filePath}.orig`;
      fs5.copyFileSync(filePath, backupPath);
      return true;
    }
  } catch (_e) {
  }
  return false;
}
__name(backupSettingsFile, "backupSettingsFile");
function restoreSettingsFromBackup(filePath) {
  try {
    const backupPath = `${filePath}.orig`;
    if (fs5.existsSync(backupPath)) {
      fs5.copyFileSync(backupPath, filePath);
      fs5.unlinkSync(backupPath);
      return true;
    }
  } catch (err) {
    console.error(
      `[settingsUtils] restoreSettingsFromBackup(${filePath}) failed:`,
      err
    );
  }
  return false;
}
__name(restoreSettingsFromBackup, "restoreSettingsFromBackup");
function cleanupSettingsBackup(filePath) {
  try {
    const backupPath = `${filePath}.orig`;
    if (fs5.existsSync(backupPath)) {
      fs5.unlinkSync(backupPath);
    }
  } catch (_e) {
  }
}
__name(cleanupSettingsBackup, "cleanupSettingsBackup");

// packages/cli/src/utils/deepMerge.ts
init_esbuild_shims();
function isPlainObject(item) {
  return !!item && typeof item === "object" && !Array.isArray(item);
}
__name(isPlainObject, "isPlainObject");
function mergeRecursively(target, source, getMergeStrategyForPath2, path9 = []) {
  for (const key of Object.keys(source)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      continue;
    }
    const newPath = [...path9, key];
    const srcValue = source[key];
    const objValue = target[key];
    const mergeStrategy = getMergeStrategyForPath2(newPath);
    if (mergeStrategy === "shallow_merge" /* SHALLOW_MERGE */ && objValue && srcValue) {
      const obj1 = typeof objValue === "object" && objValue !== null ? objValue : {};
      const obj2 = typeof srcValue === "object" && srcValue !== null ? srcValue : {};
      target[key] = { ...obj1, ...obj2 };
      continue;
    }
    if (Array.isArray(objValue)) {
      const srcArray = Array.isArray(srcValue) ? srcValue : [srcValue];
      if (mergeStrategy === "concat" /* CONCAT */) {
        target[key] = objValue.concat(srcArray);
        continue;
      }
      if (mergeStrategy === "union" /* UNION */) {
        target[key] = [...new Set(objValue.concat(srcArray))];
        continue;
      }
    }
    if (isPlainObject(objValue) && isPlainObject(srcValue)) {
      mergeRecursively(objValue, srcValue, getMergeStrategyForPath2, newPath);
    } else if (isPlainObject(srcValue)) {
      target[key] = {};
      mergeRecursively(
        target[key],
        srcValue,
        getMergeStrategyForPath2,
        newPath
      );
    } else {
      target[key] = srcValue;
    }
  }
  return target;
}
__name(mergeRecursively, "mergeRecursively");
function customDeepMerge(getMergeStrategyForPath2, ...sources) {
  const result = {};
  for (const source of sources) {
    if (source) {
      mergeRecursively(result, source, getMergeStrategyForPath2);
    }
  }
  return result;
}
__name(customDeepMerge, "customDeepMerge");

// packages/cli/src/config/migration/index.ts
init_esbuild_shims();

// packages/cli/src/config/migration/scheduler.ts
init_esbuild_shims();
var debugLogger2 = createDebugLogger("SETTINGS_MIGRATION");
function formatScope(scope) {
  if (scope === "SystemDefaults") {
    return "system default";
  }
  return scope.toLowerCase();
}
__name(formatScope, "formatScope");
var MigrationScheduler = class {
  /**
   * Creates a new MigrationScheduler with the given migrations.
   *
   * @param migrations - Array of migrations in execution order (typically ascending version)
   * @param scope - The scope of settings being migrated
   */
  constructor(migrations, scope) {
    this.migrations = migrations;
    this.scope = scope;
  }
  static {
    __name(this, "MigrationScheduler");
  }
  /**
   * Executes the migration chain on the given settings.
   *
   * Iterates through all registered migrations in order. For each migration:
   * 1. Calls `shouldMigrate` with the current settings
   * 2. If true, calls `migrate` to transform the settings
   * 3. Records the execution
   *
   * The scheduler itself has no version awareness - all version detection
   * is delegated to the individual migrations.
   *
   * @param settings - The settings object to migrate
   * @returns MigrationResult containing the final settings, version, and execution log
   */
  migrate(settings) {
    debugLogger2.debug("MigrationScheduler: Starting migration chain");
    let current = settings;
    const executed = [];
    const allWarnings = [];
    for (const migration of this.migrations) {
      try {
        if (migration.shouldMigrate(current)) {
          debugLogger2.debug(
            `MigrationScheduler: Executing migration ${migration.fromVersion} \u2192 ${migration.toVersion}`
          );
          const formattedScope = formatScope(this.scope);
          const result = migration.migrate(current, formattedScope);
          current = result.settings;
          allWarnings.push(...result.warnings);
          executed.push({
            fromVersion: migration.fromVersion,
            toVersion: migration.toVersion
          });
          debugLogger2.debug(
            `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} completed successfully`
          );
        }
      } catch (error) {
        debugLogger2.error(
          `MigrationScheduler: Migration ${migration.fromVersion} \u2192 ${migration.toVersion} failed:`,
          error
        );
        throw error;
      }
    }
    const finalVersion = current["$version"] ?? 1;
    debugLogger2.debug(
      `MigrationScheduler: Migration chain complete. Final version: ${finalVersion}, Executed: ${executed.length} migrations`
    );
    return {
      settings: current,
      finalVersion,
      executedMigrations: executed,
      warnings: allWarnings
    };
  }
};

// packages/cli/src/config/migration/versions/v1-to-v2.ts
init_esbuild_shims();

// packages/cli/src/config/migration/versions/v1-to-v2-shared.ts
init_esbuild_shims();
var V1_TO_V2_MIGRATION_MAP = {
  accessibility: "ui.accessibility",
  allowedTools: "tools.allowed",
  allowMCPServers: "mcp.allowed",
  autoAccept: "tools.autoAccept",
  autoConfigureMaxOldSpaceSize: "advanced.autoConfigureMemory",
  bugCommand: "advanced.bugCommand",
  chatCompression: "model.chatCompression",
  checkpointing: "general.checkpointing",
  coreTools: "tools.core",
  contextFileName: "context.fileName",
  customThemes: "ui.customThemes",
  customWittyPhrases: "ui.customWittyPhrases",
  debugKeystrokeLogging: "general.debugKeystrokeLogging",
  dnsResolutionOrder: "advanced.dnsResolutionOrder",
  enforcedAuthType: "security.auth.enforcedType",
  excludeTools: "tools.exclude",
  excludeMCPServers: "mcp.excluded",
  excludedProjectEnvVars: "advanced.excludedEnvVars",
  extensions: "extensions",
  fileFiltering: "context.fileFiltering",
  folderTrustFeature: "security.folderTrust.featureEnabled",
  folderTrust: "security.folderTrust.enabled",
  hasSeenIdeIntegrationNudge: "ide.hasSeenNudge",
  hideWindowTitle: "ui.hideWindowTitle",
  showStatusInTitle: "ui.showStatusInTitle",
  hideTips: "ui.hideTips",
  showLineNumbers: "ui.showLineNumbers",
  showCitations: "ui.showCitations",
  ideMode: "ide.enabled",
  includeDirectories: "context.includeDirectories",
  loadMemoryFromIncludeDirectories: "context.loadFromIncludeDirectories",
  maxSessionTurns: "model.maxSessionTurns",
  mcpServers: "mcpServers",
  mcpServerCommand: "mcp.serverCommand",
  memoryImportFormat: "context.importFormat",
  model: "model.name",
  preferredEditor: "general.preferredEditor",
  sandbox: "tools.sandbox",
  selectedAuthType: "security.auth.selectedType",
  shouldUseNodePtyShell: "tools.shell.enableInteractiveShell",
  shellPager: "tools.shell.pager",
  shellShowColor: "tools.shell.showColor",
  skipNextSpeakerCheck: "model.skipNextSpeakerCheck",
  telemetry: "telemetry",
  theme: "ui.theme",
  toolDiscoveryCommand: "tools.discoveryCommand",
  toolCallCommand: "tools.callCommand",
  usageStatisticsEnabled: "privacy.usageStatisticsEnabled",
  useExternalAuth: "security.auth.useExternal",
  useRipgrep: "tools.useRipgrep",
  vimMode: "general.vimMode",
  enableWelcomeBack: "ui.enableWelcomeBack",
  approvalMode: "tools.approvalMode",
  sessionTokenLimit: "model.sessionTokenLimit",
  contentGenerator: "model.generationConfig",
  skipLoopDetection: "model.skipLoopDetection",
  skipStartupContext: "model.skipStartupContext",
  enableOpenAILogging: "model.enableOpenAILogging",
  tavilyApiKey: "advanced.tavilyApiKey"
};
var V2_CONTAINER_KEYS = /* @__PURE__ */ new Set([
  "ui",
  "tools",
  "mcp",
  "advanced",
  "model",
  "general",
  "context",
  "security",
  "ide",
  "privacy",
  "telemetry",
  "extensions"
]);
var V1_TO_V2_PRESERVE_DISABLE_MAP = {
  disableAutoUpdate: "general.disableAutoUpdate",
  disableUpdateNag: "general.disableUpdateNag",
  disableLoadingPhrases: "ui.accessibility.disableLoadingPhrases",
  disableFuzzySearch: "context.fileFiltering.disableFuzzySearch",
  disableCacheControl: "model.generationConfig.disableCacheControl"
};
var CONSOLIDATED_DISABLE_KEYS = /* @__PURE__ */ new Set([
  "disableAutoUpdate",
  "disableUpdateNag"
]);
var V1_INDICATOR_KEYS = [
  // From V1_TO_V2_MIGRATION_MAP - keys that map to different paths in V2
  "theme",
  "model",
  "autoAccept",
  "hideTips",
  "vimMode",
  "checkpointing",
  "accessibility",
  "allowedTools",
  "allowMCPServers",
  "autoConfigureMaxOldSpaceSize",
  "bugCommand",
  "chatCompression",
  "coreTools",
  "contextFileName",
  "customThemes",
  "customWittyPhrases",
  "debugKeystrokeLogging",
  "dnsResolutionOrder",
  "enforcedAuthType",
  "excludeTools",
  "excludeMCPServers",
  "excludedProjectEnvVars",
  "fileFiltering",
  "folderTrustFeature",
  "folderTrust",
  "hasSeenIdeIntegrationNudge",
  "hideWindowTitle",
  "showStatusInTitle",
  "showLineNumbers",
  "showCitations",
  "ideMode",
  "includeDirectories",
  "loadMemoryFromIncludeDirectories",
  "maxSessionTurns",
  "mcpServerCommand",
  "memoryImportFormat",
  "preferredEditor",
  "sandbox",
  "selectedAuthType",
  "shouldUseNodePtyShell",
  "shellPager",
  "shellShowColor",
  "skipNextSpeakerCheck",
  "toolDiscoveryCommand",
  "toolCallCommand",
  "usageStatisticsEnabled",
  "useExternalAuth",
  "useRipgrep",
  "enableWelcomeBack",
  "approvalMode",
  "sessionTokenLimit",
  "contentGenerator",
  "skipLoopDetection",
  "skipStartupContext",
  "enableOpenAILogging",
  "tavilyApiKey",
  // From V1_TO_V2_PRESERVE_DISABLE_MAP - disable* keys that get nested in V2
  "disableAutoUpdate",
  "disableUpdateNag",
  "disableLoadingPhrases",
  "disableFuzzySearch",
  "disableCacheControl"
];

// packages/cli/src/config/migration/versions/v1-to-v2.ts
var V1ToV2Migration = class {
  static {
    __name(this, "V1ToV2Migration");
  }
  fromVersion = 1;
  toVersion = 2;
  /**
   * Determines whether this migration should execute.
   *
   * Decision strategy:
   * - Hard-stop when `$version` is a number >= 2 (already V2+).
   * - Otherwise, scan indicator keys and trigger only when at least one indicator is
   *   still in legacy top-level shape (primitive/array/null).
   *
   * Mixed-shape tolerance:
   * - Files that are partially migrated are supported; V2-like object-valued indicators
   *   are ignored while legacy-shaped indicators can still trigger migration.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    const version = s["$version"];
    if (typeof version === "number" && version >= 2) {
      return false;
    }
    return V1_INDICATOR_KEYS.some((key) => {
      if (!(key in s)) {
        return false;
      }
      const value = s[key];
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        return false;
      }
      return true;
    });
  }
  /**
   * Performs non-destructive V1 -> V2 transformation.
   *
   * Detailed strategy:
   * 1) Relocate known V1 keys using `V1_TO_V2_MIGRATION_MAP`.
   *    - If a source value is already an object and maps to a child path of itself
   *      (partial V2 shape), merge child properties into target path.
   * 2) Relocate disable* keys into V2 disable* locations.
   *    - Consolidated keys (`disableAutoUpdate`, `disableUpdateNag`): normalize to
   *      boolean with stable-compatible presence semantics (`value === true`).
   *    - Other disable* keys: migrate only boolean values.
   * 3) Preserve `mcpServers` top-level placement.
   * 4) Carry over remaining keys:
   *    - If a key is parent of migrated nested paths, merge unprocessed object children.
   *    - If parent value is non-object, preserve that scalar/array/null as-is.
   *    - Otherwise copy untouched key/value.
   * 5) Stamp `$version = 2`.
   *
   * The method is pure with respect to input mutation.
   */
  migrate(settings, _scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const source = settings;
    const result = {};
    const processedKeys = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [v1Key, v2Path] of Object.entries(V1_TO_V2_MIGRATION_MAP)) {
      if (v1Key in source) {
        const value = source[v1Key];
        if (V2_CONTAINER_KEYS.has(v1Key) && typeof value === "object" && value !== null && !Array.isArray(value)) {
          result[v1Key] = value;
          processedKeys.add(v1Key);
          continue;
        }
        if (typeof value === "object" && value !== null && !Array.isArray(value) && v2Path.startsWith(v1Key + ".")) {
          for (const [nestedKey, nestedValue] of Object.entries(value)) {
            setNestedPropertySafe(
              result,
              `${v2Path}.${nestedKey}`,
              nestedValue
            );
          }
        } else {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    for (const [v1Key, v2Path] of Object.entries(
      V1_TO_V2_PRESERVE_DISABLE_MAP
    )) {
      if (v1Key in source) {
        const value = source[v1Key];
        if (CONSOLIDATED_DISABLE_KEYS.has(v1Key)) {
          setNestedPropertySafe(result, v2Path, value === true);
        } else if (typeof value === "boolean") {
          setNestedPropertySafe(result, v2Path, value);
        }
        processedKeys.add(v1Key);
      }
    }
    if ("mcpServers" in source) {
      result["mcpServers"] = source["mcpServers"];
      processedKeys.add("mcpServers");
    }
    for (const key of Object.keys(source)) {
      if (!processedKeys.has(key)) {
        const isParentOfMigratedPath = Array.from(processedKeys).some(
          (processedKey) => {
            const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
            if (!v2Path) return false;
            return v2Path.startsWith(key + ".");
          }
        );
        if (isParentOfMigratedPath) {
          const existingValue = source[key];
          if (typeof existingValue === "object" && existingValue !== null && !Array.isArray(existingValue)) {
            for (const [nestedKey, nestedValue] of Object.entries(
              existingValue
            )) {
              const fullNestedPath = `${key}.${nestedKey}`;
              const wasProcessed = Array.from(processedKeys).some(
                (processedKey) => {
                  const v2Path = V1_TO_V2_MIGRATION_MAP[processedKey] || V1_TO_V2_PRESERVE_DISABLE_MAP[processedKey];
                  return v2Path === fullNestedPath;
                }
              );
              if (!wasProcessed) {
                setNestedPropertySafe(result, fullNestedPath, nestedValue);
              }
            }
          } else {
            result[key] = source[key];
          }
        } else {
          result[key] = source[key];
        }
      }
    }
    result["$version"] = 2;
    return { settings: result, warnings };
  }
};
var v1ToV2Migration = new V1ToV2Migration();

// packages/cli/src/config/migration/versions/v2-to-v3.ts
init_esbuild_shims();
var V2_TO_V3_BOOLEAN_MAP = {
  "general.disableAutoUpdate": "general.enableAutoUpdate",
  "general.disableUpdateNag": "general.enableAutoUpdate",
  "ui.accessibility.disableLoadingPhrases": "ui.accessibility.enableLoadingPhrases",
  "context.fileFiltering.disableFuzzySearch": "context.fileFiltering.enableFuzzySearch",
  "model.generationConfig.disableCacheControl": "model.generationConfig.enableCacheControl"
};
var CONSOLIDATED_V2_PATHS = {
  "general.enableAutoUpdate": [
    "general.disableAutoUpdate",
    "general.disableUpdateNag"
  ]
};
function normalizeDisableValue(value) {
  if (value === void 0) {
    return { isPresent: false, isValid: false };
  }
  if (typeof value === "boolean") {
    return { isPresent: true, isValid: true, booleanValue: value };
  }
  if (typeof value === "string") {
    const normalized = value.trim().toLowerCase();
    if (normalized === "true") {
      return { isPresent: true, isValid: true, booleanValue: true };
    }
    if (normalized === "false") {
      return { isPresent: true, isValid: true, booleanValue: false };
    }
  }
  return { isPresent: true, isValid: false };
}
__name(normalizeDisableValue, "normalizeDisableValue");
var V2ToV3Migration = class {
  static {
    __name(this, "V2ToV3Migration");
  }
  fromVersion = 2;
  toVersion = 3;
  /**
   * Migration trigger rule.
   *
   * Execute only when `$version === 2`.
   * This includes V2 files with no migratable disable* booleans so that version
   * metadata still advances to 3.
   */
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    return s["$version"] === 2;
  }
  /**
   * Applies V2 -> V3 transformation with deterministic deprecated-key cleanup.
   *
   * Detailed strategy:
   * 1) Clone input.
   * 2) Process consolidated paths first:
   *    - Inspect each source path.
   *    - Normalize each present value (boolean / coercible string / invalid).
   *    - Always delete present deprecated source key.
   *    - Valid normalized values contribute to aggregate.
   *    - Invalid values emit warnings.
   *    - Emit consolidated target when at least one valid source was consumed.
   * 3) Process remaining one-to-one mappings:
   *    - For each unmapped source, normalize value.
   *    - If valid -> delete old key and write inverted target.
   *    - If invalid -> delete old key and emit warning.
   * 4) Set `$version = 3`.
   *
   * Guarantees:
   * - Input object is not mutated.
   * - Valid migration and invalid cleanup are deterministic.
   * - Deprecated disable* keys are not retained after migration.
   */
  migrate(settings, scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const processedPaths = /* @__PURE__ */ new Set();
    const warnings = [];
    for (const [newPath, oldPaths] of Object.entries(CONSOLIDATED_V2_PATHS)) {
      let hasAnyDisable = false;
      let hasAnyBooleanValue = false;
      for (const oldPath of oldPaths) {
        const oldValue = getNestedProperty(result, oldPath);
        const normalized = normalizeDisableValue(oldValue);
        if (!normalized.isPresent) {
          continue;
        }
        deleteNestedPropertySafe(result, oldPath);
        processedPaths.add(oldPath);
        if (normalized.isValid) {
          hasAnyBooleanValue = true;
          if (normalized.booleanValue === true) {
            hasAnyDisable = true;
          }
        } else {
          warnings.push(
            `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean.`
          );
        }
      }
      if (hasAnyBooleanValue) {
        setNestedPropertySafe(result, newPath, !hasAnyDisable);
      }
    }
    for (const [oldPath, newPath] of Object.entries(V2_TO_V3_BOOLEAN_MAP)) {
      if (processedPaths.has(oldPath)) {
        continue;
      }
      const oldValue = getNestedProperty(result, oldPath);
      const normalized = normalizeDisableValue(oldValue);
      if (!normalized.isPresent) {
        continue;
      }
      deleteNestedPropertySafe(result, oldPath);
      if (normalized.isValid) {
        setNestedPropertySafe(result, newPath, !normalized.booleanValue);
      } else {
        warnings.push(
          `Removed deprecated setting '${oldPath}' from ${scope} settings because the value is invalid. Expected boolean or string "true"/"false".`
        );
      }
    }
    result["$version"] = 3;
    return { settings: result, warnings };
  }
};
var v2ToV3Migration = new V2ToV3Migration();

// packages/cli/src/config/migration/versions/v3-to-v4.ts
init_esbuild_shims();
var GIT_CO_AUTHOR_PATH = "general.gitCoAuthor";
var V3ToV4Migration = class {
  static {
    __name(this, "V3ToV4Migration");
  }
  fromVersion = 3;
  toVersion = 4;
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    if (s["$version"] === 3) {
      return true;
    }
    if (s["$version"] === void 0) {
      const value = getNestedProperty(s, GIT_CO_AUTHOR_PATH);
      if (value === void 0) return false;
      if (typeof value === "object" && value !== null && !Array.isArray(value)) {
        return false;
      }
      return true;
    }
    return false;
  }
  migrate(settings, scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const warnings = [];
    const value = getNestedProperty(result, GIT_CO_AUTHOR_PATH);
    if (typeof value === "boolean") {
      setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
        commit: value,
        pr: value
      });
    } else if (typeof value === "string") {
      const lowered = value.trim().toLowerCase();
      const disableIntent = ["false", "no", "off", "0", "disabled", ""];
      const enableIntent = ["true", "yes", "on", "1", "enabled"];
      if (enableIntent.includes(lowered)) {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: true,
          pr: true
        });
      } else if (disableIntent.includes(lowered)) {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: false,
          pr: false
        });
      } else {
        setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
          commit: false,
          pr: false
        });
        warnings.push(
          `Reset '${GIT_CO_AUTHOR_PATH}' in ${scope} settings to {commit: false, pr: false} because the stored string '${value}' was not a recognized boolean form.`
        );
      }
    } else if (value !== void 0 && (typeof value !== "object" || value === null || Array.isArray(value))) {
      setNestedPropertySafe(result, GIT_CO_AUTHOR_PATH, {
        commit: false,
        pr: false
      });
      warnings.push(
        `Reset '${GIT_CO_AUTHOR_PATH}' in ${scope} settings to {commit: false, pr: false} because the stored value was not a boolean or object.`
      );
    }
    result["$version"] = 4;
    return { settings: result, warnings };
  }
};
var v3ToV4Migration = new V3ToV4Migration();

// packages/cli/src/config/migration/versions/v5-to-v4.ts
init_esbuild_shims();
var PROVIDER_KEY_TO_PROTOCOL = {
  openai: "openai",
  "qwen-oauth": "qwen-oauth",
  gemini: "gemini",
  "vertex-ai": "gemini",
  anthropic: "anthropic"
};
function isWrappedProviderConfig(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isWrappedProviderConfig, "isWrappedProviderConfig");
var V5ToV4Migration = class {
  static {
    __name(this, "V5ToV4Migration");
  }
  fromVersion = 5;
  toVersion = 4;
  shouldMigrate(settings) {
    if (typeof settings !== "object" || settings === null) {
      return false;
    }
    const s = settings;
    if (s["$version"] === 5) {
      return true;
    }
    if (s["$version"] !== void 0) {
      return false;
    }
    const modelProviders = s["modelProviders"];
    if (typeof modelProviders !== "object" || modelProviders === null) {
      return false;
    }
    return Object.values(modelProviders).some(
      (v) => isWrappedProviderConfig(v)
    );
  }
  migrate(settings, _scope) {
    if (typeof settings !== "object" || settings === null) {
      throw new Error("Settings must be an object");
    }
    const result = structuredClone(settings);
    const warnings = [];
    const modelProviders = result["modelProviders"];
    if (typeof modelProviders === "object" && modelProviders !== null) {
      const providers = modelProviders;
      for (const [key, value] of Object.entries(providers)) {
        if (Array.isArray(value)) {
          continue;
        }
        if (!isWrappedProviderConfig(value)) {
          continue;
        }
        const derivedProtocol = Object.hasOwn(PROVIDER_KEY_TO_PROTOCOL, key) ? PROVIDER_KEY_TO_PROTOCOL[key] : void 0;
        if (typeof value.protocol === "string" && derivedProtocol !== void 0 && value.protocol !== derivedProtocol) {
          warnings.push(
            `Provider "${key}" declared protocol "${value.protocol}", but V4 derives protocol "${derivedProtocol}" from the provider key. The explicit protocol has been dropped.`
          );
        }
        providers[key] = Array.isArray(value.models) ? value.models : [];
      }
    }
    result["$version"] = 4;
    return { settings: result, warnings };
  }
};
var v5ToV4Migration = new V5ToV4Migration();

// packages/cli/src/config/migration/index.ts
var ALL_MIGRATIONS = [
  v1ToV2Migration,
  v2ToV3Migration,
  v3ToV4Migration
];
var DOWNGRADE_MIGRATIONS = [v5ToV4Migration];
var CONVERGENCE_MIGRATIONS = [
  ...ALL_MIGRATIONS,
  ...DOWNGRADE_MIGRATIONS
];
function runMigrations(settings, scope) {
  const scheduler = new MigrationScheduler([...CONVERGENCE_MIGRATIONS], scope);
  return scheduler.migrate(settings);
}
__name(runMigrations, "runMigrations");
function needsMigration(settings) {
  if (typeof settings !== "object" || settings === null) {
    return false;
  }
  const s = settings;
  const version = s["$version"];
  const hasApplicableMigration = CONVERGENCE_MIGRATIONS.some(
    (migration) => migration.shouldMigrate(settings)
  );
  if (typeof version === "number") {
    if (version === SETTINGS_VERSION) {
      return false;
    }
    return hasApplicableMigration;
  }
  return hasApplicableMigration;
}
__name(needsMigration, "needsMigration");

// packages/cli/src/config/settings.ts
var debugLogger3 = createDebugLogger("SETTINGS");
function getMergeStrategyForPath(path9) {
  let current = void 0;
  let currentSchema = getSettingsSchema();
  for (const key of path9) {
    if (!currentSchema || !currentSchema[key]) {
      return void 0;
    }
    current = currentSchema[key];
    currentSchema = current.properties;
  }
  return current?.mergeStrategy;
}
__name(getMergeStrategyForPath, "getMergeStrategyForPath");
var SETTINGS_DIRECTORY_NAME = QWEN_DIR;
function getUserSettingsPath() {
  return Storage.getGlobalSettingsPath();
}
__name(getUserSettingsPath, "getUserSettingsPath");
function getUserSettingsDir() {
  return path4.dirname(getUserSettingsPath());
}
__name(getUserSettingsDir, "getUserSettingsDir");
var DEFAULT_EXCLUDED_ENV_VARS = ["DEBUG", "DEBUG_MODE"];
var ENV_CORRUPTED_PATH = "QWEN_CODE_SETTINGS_CORRUPTED_PATH";
var ENV_WAS_RECOVERED = "QWEN_CODE_SETTINGS_WAS_RECOVERED";
var PROJECT_ENV_HARDCODED_EXCLUSIONS = [
  "QWEN_HOME",
  "QWEN_RUNTIME_DIR",
  "QWEN_CODE_MCP_APPROVALS_PATH",
  ENV_CORRUPTED_PATH,
  ENV_WAS_RECOVERED
];
var RELOAD_EXCLUDED_KEYS = /* @__PURE__ */ new Set([
  ...PROJECT_ENV_HARDCODED_EXCLUSIONS,
  "QWEN_SERVER_TOKEN",
  "QWEN_CLI_ENTRY",
  "NODE_OPTIONS",
  "NODE_PATH",
  "NODE_TLS_REJECT_UNAUTHORIZED",
  "LD_PRELOAD",
  "LD_AUDIT",
  "LD_LIBRARY_PATH",
  "DYLD_INSERT_LIBRARIES",
  "DYLD_LIBRARY_PATH",
  "BASH_ENV",
  "ENV",
  "PATH",
  "HOME",
  "TMPDIR",
  "TMP",
  "TEMP"
]);
var dotEnvSourcedKeys = /* @__PURE__ */ new Set();
var settingsEnvSourcedKeys = /* @__PURE__ */ new Set();
var lastReloadSnapshot = /* @__PURE__ */ new Map();
var lastReloadSnapshotSeeded = false;
var SETTINGS_VERSION = 4;
var SETTINGS_VERSION_KEY = "$version";
function getSystemSettingsPath() {
  if (process2.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"]) {
    return process2.env["QWEN_CODE_SYSTEM_SETTINGS_PATH"];
  }
  if (platform() === "darwin") {
    return "/Library/Application Support/QwenCode/settings.json";
  } else if (platform() === "win32") {
    return "C:\\ProgramData\\qwen-code\\settings.json";
  } else {
    return "/etc/qwen-code/settings.json";
  }
}
__name(getSystemSettingsPath, "getSystemSettingsPath");
function getSystemDefaultsPath() {
  if (process2.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"]) {
    return process2.env["QWEN_CODE_SYSTEM_DEFAULTS_PATH"];
  }
  return path4.join(
    path4.dirname(getSystemSettingsPath()),
    "system-defaults.json"
  );
}
__name(getSystemDefaultsPath, "getSystemDefaultsPath");
var SettingScope = /* @__PURE__ */ ((SettingScope2) => {
  SettingScope2["User"] = "User";
  SettingScope2["Workspace"] = "Workspace";
  SettingScope2["System"] = "System";
  SettingScope2["SystemDefaults"] = "SystemDefaults";
  return SettingScope2;
})(SettingScope || {});
function getSettingsFileKeyWarnings(settings, settingsFilePath) {
  const version = settings[SETTINGS_VERSION_KEY];
  if (typeof version !== "number" || version < SETTINGS_VERSION) {
    return [];
  }
  const warnings = [];
  const ignoredLegacyKeys = /* @__PURE__ */ new Set();
  for (const [oldKey, newPath] of Object.entries(V1_TO_V2_MIGRATION_MAP)) {
    if (oldKey === newPath) {
      continue;
    }
    if (!(oldKey in settings)) {
      continue;
    }
    const oldValue = settings[oldKey];
    if (V2_CONTAINER_KEYS.has(oldKey) && typeof oldValue === "object" && oldValue !== null && !Array.isArray(oldValue)) {
      continue;
    }
    ignoredLegacyKeys.add(oldKey);
    warnings.push(
      `Warning: Legacy setting '${oldKey}' will be ignored in ${settingsFilePath}. Please use '${newPath}' instead.`
    );
  }
  const schemaKeys = new Set(Object.keys(getSettingsSchema()));
  for (const key of Object.keys(settings)) {
    if (key === SETTINGS_VERSION_KEY) {
      continue;
    }
    if (ignoredLegacyKeys.has(key)) {
      continue;
    }
    if (schemaKeys.has(key)) {
      continue;
    }
    debugLogger3.warn(
      `Unknown setting '${key}' will be ignored in ${settingsFilePath}.`
    );
  }
  return warnings;
}
__name(getSettingsFileKeyWarnings, "getSettingsFileKeyWarnings");
function isPlainObject2(value) {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
__name(isPlainObject2, "isPlainObject");
function hasAnyProviderEntries(modelProviders) {
  if (!isPlainObject2(modelProviders)) {
    return false;
  }
  return Object.values(modelProviders).some(
    (providerModels) => Array.isArray(providerModels) && providerModels.length > 0
  );
}
__name(hasAnyProviderEntries, "hasAnyProviderEntries");
function getModelProvidersOverrideWarnings(loadedSettings) {
  if (!loadedSettings.isTrusted) {
    return [];
  }
  const userOriginal = loadedSettings.user.originalSettings;
  const workspaceOriginal = loadedSettings.workspace.originalSettings;
  if (!hasOwnModelProviders(userOriginal) || !hasOwnModelProviders(workspaceOriginal)) {
    return [];
  }
  const userModelProviders = userOriginal["modelProviders"];
  const workspaceModelProviders = workspaceOriginal["modelProviders"];
  const workspaceIsEmptyModelProviders = isPlainObject2(workspaceModelProviders) && Object.keys(workspaceModelProviders).length === 0;
  if (!workspaceIsEmptyModelProviders || !hasAnyProviderEntries(userModelProviders)) {
    return [];
  }
  return [
    `Warning: '${loadedSettings.workspace.path}' defines an empty 'modelProviders' object. This has no effect with current merge behavior, but may indicate a configuration error. If REPLACE semantics are introduced for 'modelProviders' in the future, this would override user-level model providers in '${loadedSettings.user.path}'.`
  ];
}
__name(getModelProvidersOverrideWarnings, "getModelProvidersOverrideWarnings");
function getSettingsWarnings(loadedSettings) {
  const warningSet = /* @__PURE__ */ new Set();
  for (const warning of loadedSettings.migrationWarnings) {
    warningSet.add(`Warning: ${warning}`);
  }
  for (const scope of ["User" /* User */, "Workspace" /* Workspace */]) {
    const settingsFile = loadedSettings.forScope(scope);
    if (settingsFile.rawJson === void 0) {
      continue;
    }
    const settingsObject = settingsFile.originalSettings;
    for (const warning of getSettingsFileKeyWarnings(
      settingsObject,
      settingsFile.path
    )) {
      warningSet.add(warning);
    }
  }
  for (const warning of getModelProvidersOverrideWarnings(loadedSettings)) {
    warningSet.add(warning);
  }
  return [...warningSet];
}
__name(getSettingsWarnings, "getSettingsWarnings");
function tagMcpServerScope(settings, scope) {
  const servers = settings.mcpServers;
  if (!servers || Object.keys(servers).length === 0) {
    return settings;
  }
  const tagged = {};
  for (const [name, config] of Object.entries(servers)) {
    tagged[name] = { ...config, scope };
  }
  return { ...settings, mcpServers: tagged };
}
__name(tagMcpServerScope, "tagMcpServerScope");
function mergeSettings(system, systemDefaults, user, workspace, isTrusted) {
  const safeWorkspace = isTrusted ? tagMcpServerScope(workspace, "workspace") : {};
  return customDeepMerge(
    getMergeStrategyForPath,
    {},
    // Start with an empty object
    systemDefaults,
    user,
    safeWorkspace,
    tagMcpServerScope(system, "system")
  );
}
__name(mergeSettings, "mergeSettings");
var LoadedSettings = class {
  static {
    __name(this, "LoadedSettings");
  }
  constructor(system, systemDefaults, user, workspace, isTrusted, migratedInMemorScopes, migrationWarnings = [], corruptedPath = void 0, wasRecovered = false, workspaceSettingsActive = true) {
    this.system = system;
    this.systemDefaults = systemDefaults;
    this.user = user;
    this.workspace = workspace;
    this.isTrusted = isTrusted;
    this.migratedInMemorScopes = migratedInMemorScopes;
    this.migrationWarnings = migrationWarnings;
    this.corruptedPath = corruptedPath;
    this.wasRecovered = wasRecovered;
    this.workspaceSettingsActive = workspaceSettingsActive;
    this._merged = this.computeMergedSettings();
  }
  system;
  systemDefaults;
  user;
  workspace;
  isTrusted;
  migratedInMemorScopes;
  migrationWarnings;
  corruptedPath;
  wasRecovered;
  workspaceSettingsActive;
  corruptionDialogDismissed = false;
  _merged;
  get merged() {
    return this._merged;
  }
  computeMergedSettings() {
    return mergeSettings(
      this.system.settings,
      this.systemDefaults.settings,
      this.user.settings,
      this.workspace.settings,
      this.isTrusted
    );
  }
  forScope(scope) {
    switch (scope) {
      case "User" /* User */:
        return this.user;
      case "Workspace" /* Workspace */:
        return this.workspace;
      case "System" /* System */:
        return this.system;
      case "SystemDefaults" /* SystemDefaults */:
        return this.systemDefaults;
      default:
        throw new Error(`Invalid scope: ${scope}`);
    }
  }
  setValue(scope, key, value) {
    if (key === "model.name" && typeof value === "string") {
      value = stripRuntimeSnapshotPrefix(value);
    }
    const settingsFile = this.forScope(scope);
    setNestedPropertySafe(settingsFile.settings, key, value);
    setNestedPropertySafe(settingsFile.originalSettings, key, value);
    this._merged = this.computeMergedSettings();
    const replacePath = key === "mcpServers" ? key.split(".") : [];
    saveSettings(settingsFile, createSettingsUpdate(key, value), replacePath);
  }
  recomputeMerged() {
    this._merged = this.computeMergedSettings();
  }
  reloadScopeFromDisk(scope) {
    const file = this.forScope(scope);
    try {
      if (!fs6.existsSync(file.path)) {
        file.settings = {};
        file.originalSettings = {};
        file.rawJson = void 0;
        this._merged = this.computeMergedSettings();
        return;
      }
      const content = fs6.readFileSync(file.path, "utf-8");
      const parsed = JSON.parse((0, import_strip_json_comments2.default)(content));
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        const resolved = resolveEnvVarsInObject(
          parsed,
          getHomeEnvFallbackVars()
        );
        file.settings = resolved;
        file.originalSettings = structuredClone(parsed);
        file.rawJson = content;
      }
    } catch (err) {
      debugLogger3.warn(
        `reloadScopeFromDisk(${scope}): ${getErrorMessage(err)}`
      );
    }
    this._merged = this.computeMergedSettings();
  }
  /**
   * Get user-level hooks from user settings (not merged with workspace).
   * These hooks should always be loaded regardless of folder trust.
   */
  getUserHooks() {
    return this.user.settings.hooks;
  }
  /**
   * Get project-level hooks from workspace settings (not merged).
   * Returns undefined if workspace is not trusted (hooks filtered out).
   */
  getProjectHooks() {
    if (!this.isTrusted) {
      return void 0;
    }
    return this.workspace.settings.hooks;
  }
};
function createMinimalSettings() {
  const emptySettingsFile = {
    path: "",
    settings: {},
    originalSettings: {},
    rawJson: "{}"
  };
  return new LoadedSettings(
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    emptySettingsFile,
    false,
    /* @__PURE__ */ new Set(),
    [],
    void 0,
    false
  );
}
__name(createMinimalSettings, "createMinimalSettings");
function getUserLevelEnvPaths() {
  const homeDir = homedir();
  const globalQwenDir = Storage.getGlobalQwenDir();
  const paths = /* @__PURE__ */ new Set([
    path4.normalize(path4.join(homeDir, ".env")),
    path4.normalize(path4.join(globalQwenDir, ".env"))
  ]);
  const legacyQwenEnv = path4.normalize(path4.join(homeDir, QWEN_DIR, ".env"));
  paths.add(legacyQwenEnv);
  return paths;
}
__name(getUserLevelEnvPaths, "getUserLevelEnvPaths");
var homeEnvBootstrapped = false;
function preResolveHomeEnvOverrides() {
  if (homeEnvBootstrapped) {
    return;
  }
  homeEnvBootstrapped = true;
  if (process2.env["QWEN_HOME"] && process2.env["QWEN_RUNTIME_DIR"]) {
    return;
  }
  const initialQwenHome = process2.env["QWEN_HOME"];
  const initialQwenDir = Storage.getGlobalQwenDir();
  const candidates = [path4.join(initialQwenDir, ".env")];
  if (!initialQwenHome) {
    candidates.push(path4.join(path4.dirname(initialQwenDir), ".env"));
  }
  for (const candidate of candidates) {
    readHomeEnvInto(candidate);
  }
  const discoveredQwenHome = process2.env["QWEN_HOME"];
  if (discoveredQwenHome && discoveredQwenHome !== initialQwenHome) {
    const discoveredDir = Storage.getGlobalQwenDir();
    if (discoveredDir !== initialQwenDir) {
      readHomeEnvInto(path4.join(discoveredDir, ".env"));
    }
  }
}
__name(preResolveHomeEnvOverrides, "preResolveHomeEnvOverrides");
function readHomeEnvInto(file) {
  if (!fs6.existsSync(file)) {
    return;
  }
  try {
    const parsed = dotenv.parse(fs6.readFileSync(file, "utf-8"));
    for (const key of PROJECT_ENV_HARDCODED_EXCLUSIONS) {
      if (parsed[key] && !Object.hasOwn(process2.env, key)) {
        process2.env[key] = parsed[key];
      }
    }
  } catch (_e) {
  }
}
__name(readHomeEnvInto, "readHomeEnvInto");
function getHomeEnvFallbackVars() {
  const globalQwenDir = Storage.getGlobalQwenDir();
  const candidates = [path4.join(globalQwenDir, ".env")];
  if (!process2.env["QWEN_HOME"]) {
    candidates.push(path4.join(path4.dirname(globalQwenDir), ".env"));
  }
  const result = {};
  for (const candidate of candidates) {
    if (!fs6.existsSync(candidate)) {
      continue;
    }
    try {
      const parsed = dotenv.parse(fs6.readFileSync(candidate, "utf-8"));
      for (const key in parsed) {
        if (Object.hasOwn(parsed, key) && !Object.hasOwn(process2.env, key)) {
          result[key] ??= parsed[key];
        }
      }
    } catch (e) {
      debugLogger3.warn(
        `Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`
      );
    }
  }
  return result;
}
__name(getHomeEnvFallbackVars, "getHomeEnvFallbackVars");
function detectQwenHomeRedirectWithoutMigration(activeUserSettingsPath) {
  if (!process2.env["QWEN_HOME"]) {
    return null;
  }
  const activeQwenDir = Storage.getGlobalQwenDir();
  const savedQwenHome = process2.env["QWEN_HOME"];
  delete process2.env["QWEN_HOME"];
  let legacyQwenDir;
  try {
    legacyQwenDir = Storage.getGlobalQwenDir();
  } finally {
    process2.env["QWEN_HOME"] = savedQwenHome;
  }
  if (path4.resolve(activeQwenDir) === path4.resolve(legacyQwenDir)) {
    return null;
  }
  if (fs6.existsSync(activeUserSettingsPath)) {
    return null;
  }
  const legacyUserSettings = path4.join(legacyQwenDir, "settings.json");
  if (!fs6.existsSync(legacyUserSettings)) {
    return null;
  }
  return `QWEN_HOME points to "${activeQwenDir}" but no settings.json was found there. Existing config remains at "${legacyQwenDir}" \u2014 OAuth tokens, settings, memory, extensions, and skills are not auto-migrated. Copy them manually if you want them to apply at the new location.`;
}
__name(detectQwenHomeRedirectWithoutMigration, "detectQwenHomeRedirectWithoutMigration");
function findEnvFile(settings, startDir, userLevelPaths = getUserLevelEnvPaths()) {
  const homeDir = homedir();
  const isTrusted = isWorkspaceTrusted(settings).isTrusted;
  const globalQwenDir = Storage.getGlobalQwenDir();
  const legacyQwenDir = path4.normalize(path4.join(homeDir, QWEN_DIR));
  const hasCustomConfigDir = path4.normalize(globalQwenDir) !== legacyQwenDir;
  const canUseEnvFile = /* @__PURE__ */ __name((filePath) => isTrusted !== false || userLevelPaths.has(path4.normalize(filePath)), "canUseEnvFile");
  const findHomeCandidate = /* @__PURE__ */ __name(() => {
    const candidates = [path4.join(globalQwenDir, ".env")];
    if (hasCustomConfigDir) {
      candidates.push(path4.join(legacyQwenDir, ".env"));
    }
    candidates.push(path4.join(homeDir, ".env"));
    for (const candidate of candidates) {
      if (fs6.existsSync(candidate) && canUseEnvFile(candidate)) {
        return candidate;
      }
    }
    return null;
  }, "findHomeCandidate");
  let currentDir = path4.resolve(startDir);
  let visitedHomeDir = false;
  while (true) {
    if (currentDir === homeDir) {
      visitedHomeDir = true;
      const found = findHomeCandidate();
      if (found) return found;
    } else {
      const geminiEnvPath = path4.join(currentDir, QWEN_DIR, ".env");
      if (fs6.existsSync(geminiEnvPath) && canUseEnvFile(geminiEnvPath)) {
        return geminiEnvPath;
      }
      const envPath = path4.join(currentDir, ".env");
      if (fs6.existsSync(envPath) && canUseEnvFile(envPath)) {
        return envPath;
      }
    }
    const parentDir = path4.dirname(currentDir);
    if (parentDir === currentDir || !parentDir) {
      return visitedHomeDir ? null : findHomeCandidate();
    }
    currentDir = parentDir;
  }
}
__name(findEnvFile, "findEnvFile");
function setUpCloudShellEnvironment(envFilePath) {
  if (envFilePath && fs6.existsSync(envFilePath)) {
    const envFileContent = fs6.readFileSync(envFilePath);
    const parsedEnv = dotenv.parse(envFileContent);
    if (parsedEnv["GOOGLE_CLOUD_PROJECT"]) {
      process2.env["GOOGLE_CLOUD_PROJECT"] = parsedEnv["GOOGLE_CLOUD_PROJECT"];
    } else {
      process2.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
    }
  } else {
    process2.env["GOOGLE_CLOUD_PROJECT"] = "cloudshell-gca";
  }
}
__name(setUpCloudShellEnvironment, "setUpCloudShellEnvironment");
function loadEnvironment(settings) {
  const userLevelPaths = getUserLevelEnvPaths();
  const envFilePath = findEnvFile(settings, process2.cwd(), userLevelPaths);
  if (process2.env["CLOUD_SHELL"] === "true") {
    setUpCloudShellEnvironment(envFilePath);
  }
  if (envFilePath) {
    try {
      const envFileContent = fs6.readFileSync(envFilePath, "utf-8");
      const parsedEnv = dotenv.parse(envFileContent);
      const excludedVars = settings?.advanced?.excludedEnvVars || DEFAULT_EXCLUDED_ENV_VARS;
      const normalizedEnvFilePath = path4.normalize(envFilePath);
      const isHomeScopedEnvFile = userLevelPaths.has(normalizedEnvFilePath);
      const isQwenScopedEnvFile = isHomeScopedEnvFile || path4.basename(path4.dirname(normalizedEnvFilePath)) === QWEN_DIR;
      for (const key in parsedEnv) {
        if (Object.hasOwn(parsedEnv, key)) {
          if (!isHomeScopedEnvFile && PROJECT_ENV_HARDCODED_EXCLUSIONS.includes(key)) {
            continue;
          }
          if (!isQwenScopedEnvFile && excludedVars.includes(key)) {
            continue;
          }
          if (!Object.hasOwn(process2.env, key)) {
            process2.env[key] = parsedEnv[key];
            dotEnvSourcedKeys.add(key);
          }
          if (!lastReloadSnapshotSeeded) {
            lastReloadSnapshot.set(key, parsedEnv[key]);
          }
        }
      }
    } catch (_e) {
    }
  }
  if (settings.env) {
    for (const [key, value] of Object.entries(settings.env)) {
      if (PROJECT_ENV_HARDCODED_EXCLUSIONS.includes(key)) {
        continue;
      }
      if (!Object.hasOwn(process2.env, key) && typeof value === "string") {
        process2.env[key] = value;
        settingsEnvSourcedKeys.add(key);
      }
      if (!lastReloadSnapshotSeeded && typeof value === "string" && !lastReloadSnapshot.has(key)) {
        lastReloadSnapshot.set(key, value);
      }
    }
  }
  lastReloadSnapshotSeeded = true;
}
__name(loadEnvironment, "loadEnvironment");
function reloadEnvironment(settings, workspaceCwd) {
  const userLevelPaths = getUserLevelEnvPaths();
  const envFilePath = findEnvFile(settings, workspaceCwd, userLevelPaths);
  if (process2.env["CLOUD_SHELL"] === "true") {
    setUpCloudShellEnvironment(envFilePath);
  }
  let dotEnvReadFailed = false;
  const newDotEnvKeys = /* @__PURE__ */ new Map();
  const newSettingsEnvKeys = /* @__PURE__ */ new Map();
  if (envFilePath) {
    try {
      const envFileContent = fs6.readFileSync(envFilePath, "utf-8");
      const parsedEnv = dotenv.parse(envFileContent);
      const excludedVars = settings?.advanced?.excludedEnvVars || DEFAULT_EXCLUDED_ENV_VARS;
      const normalizedEnvFilePath = path4.normalize(envFilePath);
      const isHomeScopedEnvFile = userLevelPaths.has(normalizedEnvFilePath);
      const isQwenScopedEnvFile = isHomeScopedEnvFile || path4.basename(path4.dirname(normalizedEnvFilePath)) === QWEN_DIR;
      for (const key in parsedEnv) {
        if (!Object.hasOwn(parsedEnv, key)) continue;
        if (RELOAD_EXCLUDED_KEYS.has(key)) continue;
        if (!isHomeScopedEnvFile && PROJECT_ENV_HARDCODED_EXCLUSIONS.includes(key)) {
          continue;
        }
        if (!isQwenScopedEnvFile && excludedVars.includes(key)) continue;
        newDotEnvKeys.set(key, parsedEnv[key]);
      }
    } catch {
      dotEnvReadFailed = true;
    }
  }
  if (settings.env) {
    for (const [key, value] of Object.entries(settings.env)) {
      if (RELOAD_EXCLUDED_KEYS.has(key)) continue;
      if (PROJECT_ENV_HARDCODED_EXCLUSIONS.includes(key)) continue;
      if (typeof value !== "string") continue;
      if (newDotEnvKeys.has(key)) continue;
      if (dotEnvReadFailed && lastReloadSnapshot.has(key)) continue;
      newSettingsEnvKeys.set(key, value);
    }
  }
  const allNewKeys = /* @__PURE__ */ new Set([
    ...newDotEnvKeys.keys(),
    ...newSettingsEnvKeys.keys()
  ]);
  const updatedKeys = [];
  const removedKeys = [];
  if (!dotEnvReadFailed) {
    const previouslyKnown = /* @__PURE__ */ new Set([
      ...lastReloadSnapshot.keys(),
      ...dotEnvSourcedKeys,
      ...settingsEnvSourcedKeys
    ]);
    for (const key of previouslyKnown) {
      if (!allNewKeys.has(key) && !RELOAD_EXCLUDED_KEYS.has(key)) {
        delete process2.env[key];
        removedKeys.push(key);
      }
    }
  }
  for (const [key, value] of newDotEnvKeys) {
    if (process2.env[key] !== value) {
      updatedKeys.push(key);
    }
    process2.env[key] = value;
  }
  for (const [key, value] of newSettingsEnvKeys) {
    if (process2.env[key] !== value) {
      updatedKeys.push(key);
    }
    process2.env[key] = value;
  }
  if (!dotEnvReadFailed) {
    dotEnvSourcedKeys.clear();
    for (const key of newDotEnvKeys.keys()) {
      dotEnvSourcedKeys.add(key);
    }
    lastReloadSnapshot.clear();
    for (const [key, value] of newDotEnvKeys) {
      lastReloadSnapshot.set(key, value);
    }
    for (const [key, value] of newSettingsEnvKeys) {
      lastReloadSnapshot.set(key, value);
    }
  }
  settingsEnvSourcedKeys.clear();
  for (const key of newSettingsEnvKeys.keys()) {
    settingsEnvSourcedKeys.add(key);
  }
  return { updatedKeys, removedKeys };
}
__name(reloadEnvironment, "reloadEnvironment");
var CORRUPTED_SUFFIX = ".corrupted";
function loadSettings(workspaceDir = process2.cwd(), consumeCorruptionEnvVars = true) {
  const opts = typeof consumeCorruptionEnvVars === "object" ? consumeCorruptionEnvVars : { consumeCorruptionEnvVars };
  preResolveHomeEnvOverrides();
  const userSettingsPath = getUserSettingsPath();
  const qwenHomeRedirectWarning = detectQwenHomeRedirectWithoutMigration(userSettingsPath);
  let systemSettings = {};
  let systemDefaultSettings = {};
  let userSettings = {};
  let workspaceSettings = {};
  const settingsErrors = [];
  const systemSettingsPath = getSystemSettingsPath();
  const systemDefaultsPath = getSystemDefaultsPath();
  const migratedInMemorScopes = /* @__PURE__ */ new Set();
  const resolvedWorkspaceDir = path4.resolve(workspaceDir);
  const resolvedHomeDir = path4.resolve(homedir());
  let realWorkspaceDir = resolvedWorkspaceDir;
  try {
    realWorkspaceDir = fs6.realpathSync(resolvedWorkspaceDir);
  } catch (_e) {
  }
  const realHomeDir = fs6.realpathSync(resolvedHomeDir);
  const workspaceSettingsPath = new Storage(
    workspaceDir
  ).getWorkspaceSettingsPath();
  const loadAndMigrate = /* @__PURE__ */ __name((filePath, scope) => {
    try {
      if (fs6.existsSync(filePath)) {
        const content = fs6.readFileSync(filePath, "utf-8");
        let rawSettings;
        const corruptedPath = `${filePath}${CORRUPTED_SUFFIX}`;
        let corruptedSaved = false;
        let recoveredFromEnvVar = null;
        try {
          rawSettings = JSON.parse((0, import_strip_json_comments2.default)(content));
        } catch (parseError) {
          debugLogger3.warn(
            `Settings file ${filePath} has invalid JSON (${getErrorMessage(parseError)}). Resetting to empty settings.`
          );
          try {
            fs6.copyFileSync(filePath, corruptedPath);
            corruptedSaved = true;
          } catch (copyError) {
            debugLogger3.warn(
              `Failed to copy corrupted file: ${getErrorMessage(copyError)}`
            );
          }
          if (!rawSettings) {
            const warningMsg = `Settings file ${filePath} has invalid JSON. Your settings have been reset.`;
            debugLogger3.warn(warningMsg);
            if (corruptedSaved) {
              try {
                fs6.writeFileSync(filePath, "{}", "utf-8");
              } catch {
              }
            }
            return {
              settings: {},
              migrationWarnings: [],
              corruptedPath: corruptedSaved ? corruptedPath : void 0,
              wasRecovered: false
            };
          }
        }
        const envCorruptedPath = process2.env[ENV_CORRUPTED_PATH];
        if ((opts.consumeCorruptionEnvVars ?? true) && envCorruptedPath && envCorruptedPath === corruptedPath && scope === "User" /* User */) {
          corruptedSaved = true;
          recoveredFromEnvVar = process2.env[ENV_WAS_RECOVERED] === "1";
          delete process2.env[ENV_CORRUPTED_PATH];
          delete process2.env[ENV_WAS_RECOVERED];
        }
        if (typeof rawSettings !== "object" || rawSettings === null || Array.isArray(rawSettings)) {
          settingsErrors.push({
            message: "Settings file is not a valid JSON object.",
            path: filePath
          });
          return { settings: {} };
        }
        let settingsObject = rawSettings;
        const hasVersionKey = SETTINGS_VERSION_KEY in settingsObject;
        const versionValue = settingsObject[SETTINGS_VERSION_KEY];
        const hasInvalidVersion = hasVersionKey && typeof versionValue !== "number";
        const hasLegacyNumericVersion = typeof versionValue === "number" && versionValue < SETTINGS_VERSION;
        let migrationWarnings;
        const persistSettingsObject = /* @__PURE__ */ __name((warningPrefix) => {
          try {
            const written = updateSettingsFilePreservingFormat(
              filePath,
              settingsObject,
              true
            );
            if (!written) {
              debugLogger3.error(
                `${warningPrefix}: updateSettingsFilePreservingFormat returned false for ${filePath}`
              );
            }
          } catch (e) {
            debugLogger3.error(`${warningPrefix}: ${getErrorMessage(e)}`);
          }
        }, "persistSettingsObject");
        if (needsMigration(settingsObject)) {
          const migrationResult = runMigrations(settingsObject, scope);
          if (migrationResult.executedMigrations.length > 0) {
            settingsObject = migrationResult.settings;
            migrationWarnings = migrationResult.warnings;
            persistSettingsObject("Error migrating settings file on disk");
          } else if ((hasLegacyNumericVersion || hasInvalidVersion) && !corruptedSaved) {
            settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
            debugLogger3.warn(
              `Settings version metadata in ${filePath} could not be migrated by any registered migration. Normalizing ${SETTINGS_VERSION_KEY} to ${SETTINGS_VERSION}.`
            );
            persistSettingsObject("Error normalizing settings version on disk");
          }
        } else if ((!hasVersionKey || hasInvalidVersion || hasLegacyNumericVersion) && !corruptedSaved) {
          settingsObject[SETTINGS_VERSION_KEY] = SETTINGS_VERSION;
          persistSettingsObject("Error normalizing settings version on disk");
        }
        const result = {
          settings: settingsObject,
          rawJson: content,
          migrationWarnings: migrationWarnings ?? []
        };
        if (corruptedSaved) {
          result.corruptedPath = corruptedPath;
          result.wasRecovered = recoveredFromEnvVar ?? false;
        }
        return result;
      }
    } catch (error) {
      settingsErrors.push({
        message: getErrorMessage(error),
        path: filePath
      });
    }
    return { settings: {} };
  }, "loadAndMigrate");
  const systemResult = loadAndMigrate(systemSettingsPath, "System" /* System */);
  const systemDefaultsResult = loadAndMigrate(
    systemDefaultsPath,
    "SystemDefaults" /* SystemDefaults */
  );
  const userResult = loadAndMigrate(userSettingsPath, "User" /* User */);
  let workspaceResult = {
    settings: {},
    rawJson: void 0
  };
  const workspaceSettingsActive = realWorkspaceDir !== realHomeDir;
  if (workspaceSettingsActive) {
    workspaceResult = loadAndMigrate(
      workspaceSettingsPath,
      "Workspace" /* Workspace */
    );
  }
  const systemOriginalSettings = structuredClone(systemResult.settings);
  const systemDefaultsOriginalSettings = structuredClone(
    systemDefaultsResult.settings
  );
  const userOriginalSettings = structuredClone(userResult.settings);
  const workspaceOriginalSettings = structuredClone(workspaceResult.settings);
  const homeEnvFallback = getHomeEnvFallbackVars();
  systemSettings = resolveEnvVarsInObject(
    systemResult.settings,
    homeEnvFallback
  );
  systemDefaultSettings = resolveEnvVarsInObject(
    systemDefaultsResult.settings,
    homeEnvFallback
  );
  userSettings = resolveEnvVarsInObject(userResult.settings, homeEnvFallback);
  workspaceSettings = resolveEnvVarsInObject(
    workspaceResult.settings,
    homeEnvFallback
  );
  if (userSettings.ui?.theme === "VS") {
    userSettings.ui.theme = DefaultLight.name;
  } else if (userSettings.ui?.theme === "VS2015") {
    userSettings.ui.theme = DefaultDark.name;
  }
  if (workspaceSettings.ui?.theme === "VS") {
    workspaceSettings.ui.theme = DefaultLight.name;
  } else if (workspaceSettings.ui?.theme === "VS2015") {
    workspaceSettings.ui.theme = DefaultDark.name;
  }
  const initialTrustCheckSettings = customDeepMerge(
    getMergeStrategyForPath,
    {},
    systemSettings,
    userSettings
  );
  const isTrusted = isWorkspaceTrusted(initialTrustCheckSettings).isTrusted ?? true;
  const tempMergedSettings = mergeSettings(
    systemSettings,
    systemDefaultSettings,
    userSettings,
    workspaceSettings,
    isTrusted
  );
  if (!opts.skipLoadEnvironment) {
    loadEnvironment(tempMergedSettings);
  }
  if (settingsErrors.length > 0) {
    const errorMessages = settingsErrors.map(
      (error) => `Error in ${error.path}: ${error.message}`
    );
    throw new FatalConfigError(
      `${errorMessages.join("\n")}
Please fix the configuration file(s) and try again.`
    );
  }
  const allMigrationWarnings = [
    ...qwenHomeRedirectWarning ? [qwenHomeRedirectWarning] : [],
    ...systemResult.migrationWarnings ?? [],
    ...systemDefaultsResult.migrationWarnings ?? [],
    ...userResult.migrationWarnings ?? [],
    ...workspaceResult.migrationWarnings ?? []
  ];
  return new LoadedSettings(
    {
      path: systemSettingsPath,
      settings: systemSettings,
      originalSettings: systemOriginalSettings,
      rawJson: systemResult.rawJson
    },
    {
      path: systemDefaultsPath,
      settings: systemDefaultSettings,
      originalSettings: systemDefaultsOriginalSettings,
      rawJson: systemDefaultsResult.rawJson
    },
    {
      path: userSettingsPath,
      settings: userSettings,
      originalSettings: userOriginalSettings,
      rawJson: userResult.rawJson
    },
    {
      path: workspaceSettingsPath,
      settings: workspaceSettings,
      originalSettings: workspaceOriginalSettings,
      rawJson: workspaceResult.rawJson
    },
    isTrusted,
    migratedInMemorScopes,
    allMigrationWarnings,
    userResult.corruptedPath,
    userResult.wasRecovered ?? false,
    workspaceSettingsActive
  );
}
__name(loadSettings, "loadSettings");
function createSettingsUpdate(key, value) {
  const root = {};
  setNestedPropertySafe(root, key, value);
  return root;
}
__name(createSettingsUpdate, "createSettingsUpdate");
function saveSettings(settingsFile, updates = settingsFile.originalSettings, replacePath = []) {
  try {
    const dirPath = path4.dirname(settingsFile.path);
    if (!fs6.existsSync(dirPath)) {
      fs6.mkdirSync(dirPath, { recursive: true });
    }
    const written = updateSettingsFilePreservingFormat(
      settingsFile.path,
      updates,
      false,
      replacePath
    );
    if (!written) {
      debugLogger3.error(
        `saveSettings: updateSettingsFilePreservingFormat returned false for ${settingsFile.path}`
      );
    }
  } catch (error) {
    debugLogger3.error("Error saving user settings file.");
    debugLogger3.error(error instanceof Error ? error.message : String(error));
    throw error;
  }
}
__name(saveSettings, "saveSettings");

// packages/cli/src/utils/version.ts
init_esbuild_shims();

// packages/cli/src/utils/package.ts
init_esbuild_shims();

// node_modules/read-package-up/index.js
init_esbuild_shims();
import path7 from "node:path";

// node_modules/find-up-simple/index.js
init_esbuild_shims();
import process3 from "node:process";
import fsPromises from "node:fs/promises";
import { fileURLToPath } from "node:url";
import path5 from "node:path";
var toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath, "toPath");
async function findUp(name, {
  cwd = process3.cwd(),
  type = "file",
  stopAt
} = {}) {
  let directory = path5.resolve(toPath(cwd) ?? "");
  const { root } = path5.parse(directory);
  stopAt = path5.resolve(directory, toPath(stopAt ?? root));
  const isAbsoluteName = path5.isAbsolute(name);
  while (directory) {
    const filePath = isAbsoluteName ? name : path5.join(directory, name);
    try {
      const stats = await fsPromises.stat(filePath);
      if (type === "file" && stats.isFile() || type === "directory" && stats.isDirectory()) {
        return filePath;
      }
    } catch {
    }
    if (directory === stopAt || directory === root) {
      break;
    }
    directory = path5.dirname(directory);
  }
}
__name(findUp, "findUp");

// node_modules/read-pkg/index.js
init_esbuild_shims();
import fsPromises2 from "node:fs/promises";
import path6 from "node:path";

// node_modules/parse-json/index.js
init_esbuild_shims();
var import_code_frame = __toESM(require_lib2(), 1);

// node_modules/index-to-position/index.js
init_esbuild_shims();
function getPosition(text, textIndex) {
  const lineBreakBefore = textIndex === 0 ? -1 : text.lastIndexOf("\n", textIndex - 1);
  return {
    line: lineBreakBefore === -1 ? 0 : text.slice(0, lineBreakBefore + 1).match(/\n/g).length,
    column: textIndex - lineBreakBefore - 1
  };
}
__name(getPosition, "getPosition");
function indexToPosition(text, textIndex, { oneBased = false } = {}) {
  if (typeof text !== "string") {
    throw new TypeError("Text parameter should be a string");
  }
  if (!Number.isInteger(textIndex)) {
    throw new TypeError("Index parameter should be an integer");
  }
  if (textIndex < 0 || textIndex > text.length) {
    throw new RangeError("Index out of bounds");
  }
  const position = getPosition(text, textIndex);
  return oneBased ? { line: position.line + 1, column: position.column + 1 } : position;
}
__name(indexToPosition, "indexToPosition");

// node_modules/parse-json/index.js
var getCodePoint = /* @__PURE__ */ __name((character) => `\\u{${character.codePointAt(0).toString(16)}}`, "getCodePoint");
var JSONError = class _JSONError extends Error {
  static {
    __name(this, "JSONError");
  }
  name = "JSONError";
  fileName;
  #input;
  #jsonParseError;
  #message;
  #codeFrame;
  #rawCodeFrame;
  constructor(messageOrOptions) {
    if (typeof messageOrOptions === "string") {
      super();
      this.#message = messageOrOptions;
    } else {
      const { jsonParseError, fileName, input } = messageOrOptions;
      super(void 0, { cause: jsonParseError });
      this.#input = input;
      this.#jsonParseError = jsonParseError;
      this.fileName = fileName;
    }
    Error.captureStackTrace?.(this, _JSONError);
  }
  get message() {
    this.#message ??= `${addCodePointToUnexpectedToken(this.#jsonParseError.message)}${this.#input === "" ? " while parsing empty string" : ""}`;
    const { codeFrame } = this;
    return `${this.#message}${this.fileName ? ` in ${this.fileName}` : ""}${codeFrame ? `

${codeFrame}
` : ""}`;
  }
  set message(message) {
    this.#message = message;
  }
  #getCodeFrame(highlightCode) {
    if (!this.#jsonParseError) {
      return;
    }
    const input = this.#input;
    const location = getErrorLocation(input, this.#jsonParseError.message);
    if (!location) {
      return;
    }
    return (0, import_code_frame.codeFrameColumns)(input, { start: location }, { highlightCode });
  }
  get codeFrame() {
    this.#codeFrame ??= this.#getCodeFrame(
      /* highlightCode */
      true
    );
    return this.#codeFrame;
  }
  get rawCodeFrame() {
    this.#rawCodeFrame ??= this.#getCodeFrame(
      /* highlightCode */
      false
    );
    return this.#rawCodeFrame;
  }
};
var getErrorLocation = /* @__PURE__ */ __name((string, message) => {
  const match = message.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);
  if (!match) {
    return;
  }
  const { index, line, column } = match.groups;
  if (line && column) {
    return { line: Number(line), column: Number(column) };
  }
  return indexToPosition(string, Number(index), { oneBased: true });
}, "getErrorLocation");
var addCodePointToUnexpectedToken = /* @__PURE__ */ __name((message) => message.replace(
  // TODO[engine:node@>=20]: The token always quoted after Node.js 20
  /(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,
  (_, _quote, token) => `"${token}"(${getCodePoint(token)})`
), "addCodePointToUnexpectedToken");
function parseJson(string, reviver, fileName) {
  if (typeof reviver === "string") {
    fileName = reviver;
    reviver = void 0;
  }
  try {
    return JSON.parse(string, reviver);
  } catch (error) {
    throw new JSONError({
      jsonParseError: error,
      fileName,
      input: string
    });
  }
}
__name(parseJson, "parseJson");

// node_modules/read-pkg/index.js
var import_normalize_package_data = __toESM(require_normalize(), 1);

// node_modules/unicorn-magic/node.js
init_esbuild_shims();
import { fileURLToPath as fileURLToPath2 } from "node:url";
function toPath2(urlOrPath) {
  return urlOrPath instanceof URL ? fileURLToPath2(urlOrPath) : urlOrPath;
}
__name(toPath2, "toPath");

// node_modules/read-pkg/index.js
var getPackagePath = /* @__PURE__ */ __name((cwd) => path6.resolve(toPath2(cwd) ?? ".", "package.json"), "getPackagePath");
var _readPackage = /* @__PURE__ */ __name((file, normalize3) => {
  const json = typeof file === "string" ? parseJson(file) : file;
  if (normalize3) {
    (0, import_normalize_package_data.default)(json);
  }
  return json;
}, "_readPackage");
async function readPackage({ cwd, normalize: normalize3 = true } = {}) {
  const packageFile = await fsPromises2.readFile(getPackagePath(cwd), "utf8");
  return _readPackage(packageFile, normalize3);
}
__name(readPackage, "readPackage");

// node_modules/read-package-up/index.js
async function readPackageUp(options) {
  const filePath = await findUp("package.json", options);
  if (!filePath) {
    return;
  }
  return {
    packageJson: await readPackage({ ...options, cwd: path7.dirname(filePath) }),
    path: filePath
  };
}
__name(readPackageUp, "readPackageUp");

// packages/cli/src/utils/package.ts
import { fileURLToPath as fileURLToPath3 } from "node:url";
import path8 from "node:path";
var __filename = fileURLToPath3(import.meta.url);
var __dirname = path8.dirname(__filename);
var packageJson;
async function getPackageJson() {
  if (packageJson) {
    return packageJson;
  }
  const result = await readPackageUp({ cwd: __dirname });
  if (!result) {
    return;
  }
  packageJson = result.packageJson;
  return packageJson;
}
__name(getPackageJson, "getPackageJson");

// packages/cli/src/utils/version.ts
async function getCliVersion() {
  const pkgJson = await getPackageJson();
  return "0.19.1";
}
__name(getCliVersion, "getCliVersion");

// packages/cli/src/ui/utils/formatters.ts
init_esbuild_shims();
var formatMemoryUsage = /* @__PURE__ */ __name((bytes) => {
  const gb = bytes / (1024 * 1024 * 1024);
  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }
  if (bytes < 1024 * 1024 * 1024) {
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
  return `${gb.toFixed(2)} GB`;
}, "formatMemoryUsage");
var formatRelativeTime = /* @__PURE__ */ __name((timestamp) => {
  const now = Date.now();
  const diffMs = now - timestamp;
  const seconds = Math.floor(diffMs / 1e3);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const weeks = Math.floor(days / 7);
  const months = Math.floor(days / 30);
  if (months > 0) {
    return months === 1 ? "1 month ago" : `${months} months ago`;
  }
  if (weeks > 0) {
    return weeks === 1 ? "1 week ago" : `${weeks} weeks ago`;
  }
  if (days > 0) {
    return days === 1 ? "1 day ago" : `${days} days ago`;
  }
  if (hours > 0) {
    return hours === 1 ? "1 hour ago" : `${hours} hours ago`;
  }
  if (minutes > 0) {
    return minutes === 1 ? "1 minute ago" : `${minutes} minutes ago`;
  }
  return "just now";
}, "formatRelativeTime");
var formatTokenCount = /* @__PURE__ */ __name((count) => {
  if (count < 1e3) {
    return `${count}`;
  }
  if (count < 1e4) {
    return `${(count / 1e3).toFixed(1)}k`;
  }
  return `${Math.floor(count / 1e3)}k`;
}, "formatTokenCount");
var formatDuration = /* @__PURE__ */ __name((milliseconds, options) => {
  if (milliseconds <= 0) {
    return "0s";
  }
  if (milliseconds < 1e3) {
    return `${Math.round(milliseconds)}ms`;
  }
  const totalSeconds = milliseconds / 1e3;
  if (totalSeconds < 60) {
    const formatted = totalSeconds.toFixed(1);
    if (parseFloat(formatted) >= 60) {
      return "1m";
    }
    if (options?.hideTrailingZeros && formatted.endsWith(".0")) {
      return `${formatted.slice(0, -2)}s`;
    }
    return `${formatted}s`;
  }
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = Math.floor(totalSeconds % 60);
  const parts = [];
  if (hours > 0) {
    parts.push(`${hours}h`);
  }
  if (minutes > 0) {
    parts.push(`${minutes}m`);
  }
  if (seconds > 0) {
    parts.push(`${seconds}s`);
  }
  if (parts.length === 0) {
    if (hours > 0) return `${hours}h`;
    if (minutes > 0) return `${minutes}m`;
    return `${seconds}s`;
  }
  return parts.join(" ");
}, "formatDuration");

// packages/cli/src/config/loadedSettingsAdapter.ts
init_esbuild_shims();
function createLoadedSettingsAdapter(settings, scope) {
  const persistScope = scope ?? getPersistScopeForModelSelection(settings);
  const settingsFile = settings.forScope(persistScope);
  let settingsSnapshot = null;
  let originalSnapshot = null;
  return {
    getValue(key) {
      return getNestedProperty(settings.merged, key);
    },
    setValue(key, value) {
      for (const part of key.split(".")) {
        if (part === "__proto__" || part === "constructor" || part === "prototype") {
          throw new Error(
            `Refusing to write settings key with reserved segment: ${key}`
          );
        }
      }
      settings.setValue(persistScope, key, value);
    },
    getModelProviders() {
      return settings.merged.modelProviders ?? {};
    },
    persist() {
    },
    backup() {
      backupSettingsFile(settingsFile.path);
      settingsSnapshot = structuredClone(settingsFile.settings);
      originalSnapshot = structuredClone(settingsFile.originalSettings);
    },
    restore() {
      const restored = restoreSettingsFromBackup(settingsFile.path);
      if (!restored) {
        console.error(
          `[loadedSettingsAdapter] On-disk rollback of ${settingsFile.path} failed; in-memory state was restored but the file may be inconsistent. Re-run /auth or inspect the file directly to recover.`
        );
      }
      if (settingsSnapshot !== null) {
        settingsFile.settings = settingsSnapshot;
      }
      if (originalSnapshot !== null) {
        settingsFile.originalSettings = originalSnapshot;
      }
      settings.recomputeMerged();
    },
    cleanupBackup() {
      cleanupSettingsBackup(settingsFile.path);
      settingsSnapshot = null;
      originalSnapshot = null;
    }
  };
}
__name(createLoadedSettingsAdapter, "createLoadedSettingsAdapter");

// packages/cli/src/utils/acpModelUtils.ts
init_esbuild_shims();
function formatAcpModelId(modelId, authType) {
  return `${modelId}(${authType})`;
}
__name(formatAcpModelId, "formatAcpModelId");
function sanitizeProviderBaseUrl(baseUrl) {
  const scheme = baseUrl.match(/^[A-Za-z][A-Za-z\d+.-]*:\/\//);
  if (!scheme) {
    return baseUrl;
  }
  const authorityStart = scheme[0].length;
  const stripAt = /* @__PURE__ */ __name((at) => `${baseUrl.slice(0, authorityStart)}${baseUrl.slice(at + 1)}`, "stripAt");
  const authorityEnd = findAuthorityEnd(baseUrl, authorityStart);
  const authorityAt = baseUrl.slice(authorityStart, authorityEnd).lastIndexOf("@");
  const authorityAtIndex = authorityAt === -1 ? -1 : authorityStart + authorityAt;
  try {
    const parsed = new URL(baseUrl);
    if (parsed.username || parsed.password) {
      return authorityAtIndex >= authorityStart ? stripAt(authorityAtIndex) : baseUrl;
    }
    return baseUrl;
  } catch {
    if (authorityAtIndex >= authorityStart) {
      return stripAt(authorityAtIndex);
    }
    const fallbackAt = findUnescapedUserInfoFallbackAt(
      baseUrl,
      authorityStart,
      authorityEnd
    );
    return fallbackAt === -1 ? baseUrl : stripAt(fallbackAt);
  }
}
__name(sanitizeProviderBaseUrl, "sanitizeProviderBaseUrl");
function findUnescapedUserInfoFallbackAt(baseUrl, authorityStart, authorityEnd) {
  const at = baseUrl.lastIndexOf("@");
  if (at < authorityStart || authorityEnd >= at) {
    return -1;
  }
  const colon = baseUrl.indexOf(":", authorityStart);
  if (colon === -1 || colon > authorityEnd) {
    return -1;
  }
  const portCandidate = baseUrl.slice(colon + 1, authorityEnd);
  return /^\d+$/.test(portCandidate) ? -1 : at;
}
__name(findUnescapedUserInfoFallbackAt, "findUnescapedUserInfoFallbackAt");
function findAuthorityEnd(baseUrl, authorityStart) {
  const slash = baseUrl.indexOf("/", authorityStart);
  const query = baseUrl.indexOf("?", authorityStart);
  const hash = baseUrl.indexOf("#", authorityStart);
  let end = baseUrl.length;
  if (slash !== -1) end = Math.min(end, slash);
  if (query !== -1) end = Math.min(end, query);
  if (hash !== -1) end = Math.min(end, hash);
  return end;
}
__name(findAuthorityEnd, "findAuthorityEnd");
function parseAcpBaseModelId(value) {
  const trimmed = value.trim();
  const closeIdx = trimmed.lastIndexOf(")");
  const openIdx = trimmed.lastIndexOf("(");
  if (openIdx >= 0 && closeIdx === trimmed.length - 1 && openIdx < closeIdx) {
    return trimmed.slice(0, openIdx);
  }
  return trimmed;
}
__name(parseAcpBaseModelId, "parseAcpBaseModelId");
function parseAcpModelOption(input) {
  const trimmed = input.trim();
  const closeIdx = trimmed.lastIndexOf(")");
  const openIdx = trimmed.lastIndexOf("(");
  if (openIdx >= 0 && closeIdx === trimmed.length - 1 && openIdx < closeIdx) {
    const maybeModelId = trimmed.slice(0, openIdx);
    const maybeAuthType = trimmed.slice(openIdx + 1, closeIdx);
    const parsedAuthType = external_exports.nativeEnum(AuthType).safeParse(maybeAuthType);
    if (parsedAuthType.success) {
      return { modelId: maybeModelId, authType: parsedAuthType.data };
    }
  }
  return { modelId: trimmed };
}
__name(parseAcpModelOption, "parseAcpModelOption");

// packages/cli/src/utils/modelConfigUtils.ts
init_esbuild_shims();
var AUTH_ENV_MODEL_VARS = {
  ["openai" /* USE_OPENAI */]: ["OPENAI_MODEL", "QWEN_MODEL"],
  ["gemini" /* USE_GEMINI */]: ["GEMINI_MODEL"],
  ["vertex-ai" /* USE_VERTEX_AI */]: ["GOOGLE_MODEL"],
  ["anthropic" /* USE_ANTHROPIC */]: ["ANTHROPIC_MODEL"],
  ["qwen-oauth" /* QWEN_OAUTH */]: []
};
function getIgnoredTopLevelGenerationConfigFields(settingsGenerationConfig, modelProvider) {
  if (!settingsGenerationConfig || !modelProvider) {
    return [];
  }
  const providerGenerationConfig = modelProvider.generationConfig ?? {};
  return MODEL_GENERATION_CONFIG_FIELDS.filter(
    (field) => Object.hasOwn(settingsGenerationConfig, field) && !Object.hasOwn(providerGenerationConfig, field)
  );
}
__name(getIgnoredTopLevelGenerationConfigFields, "getIgnoredTopLevelGenerationConfigFields");
function buildIgnoredTopLevelGenerationConfigWarning(authType, modelProvider, ignoredFields) {
  if (ignoredFields.length === 0) {
    return void 0;
  }
  const fieldList = ignoredFields.map((field) => `model.generationConfig.${field}`).join(", ");
  const isSingular = ignoredFields.length === 1;
  const verb = isSingular ? "is" : "are";
  const fieldReference = isSingular ? "this field" : "these fields";
  const pronoun = isSingular ? "it" : "them";
  return `Warning: ${fieldList} ${verb} ignored for provider model "${modelProvider.id}" from modelProviders.${authType}. Move ${fieldReference} to modelProviders.${authType}[].generationConfig for that model if you want ${pronoun} to apply.`;
}
__name(buildIgnoredTopLevelGenerationConfigWarning, "buildIgnoredTopLevelGenerationConfigWarning");
function getAuthTypeFromEnv() {
  if (process.env["QWEN_OAUTH"]) {
    return "qwen-oauth" /* QWEN_OAUTH */;
  }
  if (process.env["OPENAI_API_KEY"] && (process.env["OPENAI_MODEL"] || process.env["QWEN_MODEL"]) && process.env["OPENAI_BASE_URL"]) {
    return "openai" /* USE_OPENAI */;
  }
  if (process.env["GEMINI_API_KEY"] && process.env["GEMINI_MODEL"]) {
    return "gemini" /* USE_GEMINI */;
  }
  if (process.env["GOOGLE_API_KEY"] && process.env["GOOGLE_MODEL"]) {
    return "vertex-ai" /* USE_VERTEX_AI */;
  }
  if (process.env["ANTHROPIC_API_KEY"] && process.env["ANTHROPIC_MODEL"] && process.env["ANTHROPIC_BASE_URL"]) {
    return "anthropic" /* USE_ANTHROPIC */;
  }
  return void 0;
}
__name(getAuthTypeFromEnv, "getAuthTypeFromEnv");
function resolveCliGenerationConfig(inputs) {
  const { argv, settings, selectedAuthType } = inputs;
  const env = inputs.env ?? process.env;
  const authType = selectedAuthType;
  let resolvedModel;
  let sourceEnvVar;
  let resolvedFromSettings = false;
  if (argv.model) {
    resolvedModel = argv.model;
  } else if (settings.model?.name) {
    resolvedModel = stripRuntimeSnapshotPrefix(settings.model.name);
    resolvedFromSettings = true;
  } else if (authType && AUTH_ENV_MODEL_VARS[authType]) {
    for (const envVar of AUTH_ENV_MODEL_VARS[authType]) {
      if (env[envVar]) {
        resolvedModel = env[envVar];
        sourceEnvVar = envVar;
        break;
      }
    }
  }
  let modelProvider;
  let disambiguationWarning;
  if (resolvedModel && authType && settings.modelProviders) {
    const providers = settings.modelProviders[authType];
    if (providers && Array.isArray(providers)) {
      const persistedBaseUrl = settings.model?.baseUrl;
      if (resolvedFromSettings && persistedBaseUrl) {
        const exactMatch = providers.find(
          (p) => p.id === resolvedModel && p.baseUrl === persistedBaseUrl
        );
        modelProvider = exactMatch ?? providers.find((p) => p.id === resolvedModel);
        if (!exactMatch && modelProvider) {
          const fallbackBaseUrl = modelProvider.baseUrl === void 0 ? "(default baseUrl)" : sanitizeProviderBaseUrl(modelProvider.baseUrl);
          disambiguationWarning = `Persisted model.baseUrl '${sanitizeProviderBaseUrl(persistedBaseUrl)}' no longer matches any provider for model '${resolvedModel}' (authType '${authType}'); using the first id match ('${fallbackBaseUrl}'). Re-select the model to update it.`;
        }
      } else {
        modelProvider = providers.find((p) => p.id === resolvedModel);
      }
    }
  }
  const allModelEnvVars = Object.values(AUTH_ENV_MODEL_VARS).flat();
  const filteredEnv = { ...env };
  if (sourceEnvVar) {
    for (const envVar of allModelEnvVars) {
      if (envVar !== sourceEnvVar) {
        delete filteredEnv[envVar];
      }
    }
  } else {
    for (const envVar of allModelEnvVars) {
      delete filteredEnv[envVar];
    }
  }
  const configSources = {
    authType,
    cli: {
      model: argv.model,
      apiKey: argv.openaiApiKey,
      baseUrl: argv.openaiBaseUrl
    },
    settings: {
      model: settings.model?.name ? stripRuntimeSnapshotPrefix(settings.model.name) : void 0,
      apiKey: settings.security?.auth?.apiKey,
      baseUrl: settings.security?.auth?.baseUrl,
      generationConfig: settings.model?.generationConfig
    },
    modelProvider,
    env: filteredEnv
  };
  const resolved = resolveModelConfig(configSources);
  const ignoredGenerationConfigWarning = authType && modelProvider ? buildIgnoredTopLevelGenerationConfigWarning(
    authType,
    modelProvider,
    getIgnoredTopLevelGenerationConfigFields(
      settings.model?.generationConfig,
      modelProvider
    )
  ) : void 0;
  const enableOpenAILogging = (typeof argv.openaiLogging === "undefined" ? settings.model?.enableOpenAILogging : argv.openaiLogging) ?? false;
  const openAILoggingDir = argv.openaiLoggingDir || settings.model?.openAILoggingDir;
  const generationConfig = {
    ...resolved.config,
    enableOpenAILogging,
    openAILoggingDir
  };
  return {
    model: resolved.config.model || "",
    apiKey: resolved.config.apiKey || "",
    baseUrl: resolved.config.baseUrl || "",
    generationConfig,
    sources: resolved.sources,
    warnings: [
      ...resolved.warnings,
      ...disambiguationWarning ? [disambiguationWarning] : [],
      ...ignoredGenerationConfigWarning ? [ignoredGenerationConfigWarning] : []
    ]
  };
}
__name(resolveCliGenerationConfig, "resolveCliGenerationConfig");

// packages/acp-bridge/src/bridgeTypes.ts
init_esbuild_shims();
var MID_TURN_QUEUE_DRAIN_METHOD = "craft/drainMidTurnQueue";

// packages/cli/src/utils/systemInfo.ts
init_esbuild_shims();
import process4 from "node:process";
import os from "node:os";
import { execFile } from "node:child_process";

// packages/cli/src/generated/git-commit.ts
init_esbuild_shims();
var GIT_COMMIT_INFO = "cf34fccc51";

// packages/cli/src/utils/systemInfo.ts
var debugLogger4 = createDebugLogger("STATUS");
var VERSION_PROBE_TIMEOUT_MS = 5e3;
function probeVersion(binary) {
  return new Promise((resolve3) => {
    execFile(
      binary,
      ["--version"],
      { timeout: VERSION_PROBE_TIMEOUT_MS, encoding: "utf-8" },
      (err, stdout) => {
        if (err) {
          resolve3("unknown");
          return;
        }
        resolve3(typeof stdout === "string" ? stdout.trim() : "unknown");
      }
    );
  });
}
__name(probeVersion, "probeVersion");
async function getNpmVersion() {
  return probeVersion("npm");
}
__name(getNpmVersion, "getNpmVersion");
async function getGitVersion() {
  return probeVersion("git");
}
__name(getGitVersion, "getGitVersion");
async function getIdeClientName(context) {
  if (!context.services.config?.getIdeMode()) {
    return "";
  }
  try {
    const ideClient = await IdeClient.getInstance();
    return ideClient?.getDetectedIdeDisplayName() ?? "";
  } catch {
    return "";
  }
}
__name(getIdeClientName, "getIdeClientName");
function getSandboxEnv(stripPrefix = false) {
  const sandbox = process4.env["SANDBOX"];
  if (!sandbox || sandbox === "sandbox-exec") {
    if (sandbox === "sandbox-exec") {
      const profile = process4.env["SEATBELT_PROFILE"] || "unknown";
      return `sandbox-exec (${profile})`;
    }
    return "no sandbox";
  }
  if (stripPrefix) {
    return sandbox.replace(/^qwen-(?:code-)?/, "");
  }
  return sandbox;
}
__name(getSandboxEnv, "getSandboxEnv");
async function getSystemInfo(context) {
  const osPlatform = process4.platform;
  const osArch = process4.arch;
  const osRelease = os.release();
  const nodeVersion = process4.version;
  const npmVersion = await getNpmVersion();
  const sandboxEnv = getSandboxEnv();
  const modelVersion = context.services.config?.getModel() || "Unknown";
  const cliVersion = await getCliVersion();
  const selectedAuthType = context.services.config?.getAuthType() || "";
  const ideClient = await getIdeClientName(context);
  const sessionId = context.services.config?.getSessionId() || "unknown";
  const proxy = context.services.config?.getProxy();
  return {
    cliVersion,
    osPlatform,
    osArch,
    osRelease,
    nodeVersion,
    npmVersion,
    sandboxEnv,
    modelVersion,
    selectedAuthType,
    ideClient,
    sessionId,
    proxy
  };
}
__name(getSystemInfo, "getSystemInfo");
async function getExtendedSystemInfo(context) {
  const baseInfo = await getSystemInfo(context);
  const memoryUsage = formatMemoryUsage(process4.memoryUsage().rss);
  const sandboxEnv = getSandboxEnv(true);
  const contentGeneratorConfig = baseInfo.selectedAuthType === "openai" /* USE_OPENAI */ || baseInfo.selectedAuthType === "anthropic" /* USE_ANTHROPIC */ ? context.services.config?.getContentGeneratorConfig() : void 0;
  const baseUrl = contentGeneratorConfig?.baseUrl;
  const apiKeyEnvKey = contentGeneratorConfig?.apiKeyEnvKey;
  const gitCommit = GIT_COMMIT_INFO && !["N/A"].includes(GIT_COMMIT_INFO) ? GIT_COMMIT_INFO : void 0;
  const fastModel = context.services.settings?.merged?.fastModel || void 0;
  const lspStatus = getLspStatus(context);
  return {
    ...baseInfo,
    sandboxEnv,
    memoryUsage,
    baseUrl,
    apiKeyEnvKey,
    gitCommit,
    fastModel,
    lspStatus
  };
}
__name(getExtendedSystemInfo, "getExtendedSystemInfo");
function getLspStatus(context) {
  try {
    const snapshot = context.services.config?.getLspStatusSnapshot?.();
    if (!snapshot) {
      return void 0;
    }
    if (context.services.config?.getDebugMode?.()) {
      debugLogger4.debug("LSP status snapshot for /status:", snapshot);
    }
    return formatLspStatusSnapshot(snapshot);
  } catch (error) {
    if (context.services.config?.getDebugMode?.()) {
      debugLogger4.debug(
        "Unable to read LSP status snapshot for /status:",
        error
      );
    }
    return void 0;
  }
}
__name(getLspStatus, "getLspStatus");
function formatLspStatusSnapshot(snapshot) {
  if (!snapshot.enabled) {
    return "disabled";
  }
  if (snapshot.initializationError) {
    return `enabled, initialization failed: ${snapshot.initializationError}`;
  }
  if (snapshot.statusUnavailable) {
    return "enabled, status unavailable";
  }
  if (snapshot.configuredServers === 0) {
    return "enabled, no servers configured";
  }
  const details = [
    snapshot.failedServers > 0 ? `${snapshot.failedServers} failed` : "",
    snapshot.inProgressServers > 0 ? `${snapshot.inProgressServers} starting` : "",
    snapshot.notStartedServers > 0 ? `${snapshot.notStartedServers} not started` : ""
  ].filter(Boolean);
  const detailText = details.length > 0 ? ` (${details.join(", ")})` : "";
  return `enabled, ${snapshot.readyServers}/${snapshot.configuredServers} ready${detailText}`;
}
__name(formatLspStatusSnapshot, "formatLspStatusSnapshot");

export {
  require_strip_json_comments,
  resolveColor,
  subtleBandColor,
  supportsTrueColor,
  lightTheme,
  darkTheme,
  ansiTheme,
  Theme,
  createCustomTheme,
  validateCustomTheme,
  DefaultLight,
  DefaultDark,
  loadTrustedFolders,
  isFolderTrustEnabled,
  isWorkspaceTrusted,
  getPersistScopeForModelSelection,
  TOGGLE_TYPES,
  OUTPUT_LANGUAGE_AUTO,
  isAutoLanguage,
  resolveOutputLanguage,
  getOutputLanguageFilePath,
  updateOutputLanguageFile,
  writeOutputLanguageAndRegisterPath,
  initializeLlmOutputLanguage,
  getFlattenedSchema,
  getSettingDefinition,
  requiresRestart,
  getDefaultValue,
  getNestedValue,
  getNestedProperty,
  getEffectiveValue,
  getDialogSettingKeys,
  settingExistsInScope,
  setPendingSettingValue,
  setPendingSettingValueAny,
  getRestartRequiredFromModified,
  saveModifiedSettings,
  getDisplayValue,
  isDefaultValue,
  SETTINGS_DIRECTORY_NAME,
  getUserSettingsDir,
  ENV_CORRUPTED_PATH,
  ENV_WAS_RECOVERED,
  SettingScope,
  getSettingsWarnings,
  createMinimalSettings,
  preResolveHomeEnvOverrides,
  loadEnvironment,
  reloadEnvironment,
  CORRUPTED_SUFFIX,
  loadSettings,
  formatAcpModelId,
  sanitizeProviderBaseUrl,
  parseAcpBaseModelId,
  parseAcpModelOption,
  getAuthTypeFromEnv,
  resolveCliGenerationConfig,
  require_debug,
  require_constants,
  require_re,
  require_parse_options,
  require_identifiers,
  require_semver,
  require_parse2 as require_parse,
  require_valid,
  require_clean,
  getPackageJson,
  getCliVersion,
  EVENT_SCHEMA_VERSION,
  DEFAULT_RING_SIZE,
  SubscriberLimitExceededError,
  EventBus,
  canonicalizeWorkspace,
  MAX_WORKSPACE_PATH_LENGTH,
  NOT_CURRENTLY_GENERATING_CANCEL_MESSAGE,
  isNotCurrentlyGeneratingCancelError,
  SessionNotFoundError,
  RestoreInProgressError,
  InvalidSessionScopeError,
  SessionLimitExceededError,
  PromptQueueFullError,
  WorkspaceMismatchError,
  InvalidClientIdError,
  SessionShellDisabledError,
  SessionShellClientRequiredError,
  InvalidPermissionOptionError,
  InvalidSessionMetadataError,
  PermissionPolicyNotImplementedError,
  CancelSentinelCollisionError,
  PermissionForbiddenError,
  WorkspaceInitConflictError,
  WorkspaceInitPathEscapeError,
  WorkspaceInitSymlinkError,
  WorkspaceInitRaceError,
  McpServerNotFoundError,
  McpServerRestartFailedError,
  SessionBusyError,
  InvalidRewindTargetError,
  BranchWhilePromptActiveError,
  STATUS_SCHEMA_VERSION,
  SERVE_ERROR_KINDS,
  BridgeTimeoutError,
  BridgeChannelClosedError,
  MissingCliEntryError,
  SERVE_STATUS_EXT_METHODS,
  SERVE_CONTROL_EXT_METHODS,
  IDLE_HOOK_EVENTS,
  createIdleWorkspaceExtensionsStatus,
  createIdleWorkspaceHooksStatus,
  createIdleWorkspaceMemoryStatus,
  createIdleWorkspaceMcpStatus,
  createIdleWorkspaceSkillsStatus,
  createIdleWorkspaceProvidersStatus,
  createIdleEnvStatus,
  ACP_PREFLIGHT_KINDS,
  createIdleAcpPreflightCells,
  mapDomainErrorToErrorKind,
  MID_TURN_QUEUE_DRAIN_METHOD,
  formatMemoryUsage,
  formatRelativeTime,
  formatTokenCount,
  formatDuration,
  getNpmVersion,
  getGitVersion,
  getExtendedSystemInfo,
  createLoadedSettingsAdapter
};
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen team
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen Team
 * SPDX-License-Identifier: Apache-2.0
 *
 * Adapter that lets core's `applyProviderInstallPlan` write through
 * `LoadedSettings` while preserving CLI-specific guarantees:
 * - scope resolution via `getPersistScopeForModelSelection`
 * - on-disk `.orig` backup of the target settings file
 * - in-memory snapshot of `settings` / `originalSettings` for rollback
 * - merged-settings recomputation after restore
 */
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2025 Qwen
 * SPDX-License-Identifier: Apache-2.0
 */
/*! Bundled license information:

repeat-string/index.js:
  (*!
   * repeat-string <https://github.com/jonschlinkert/repeat-string>
   *
   * Copyright (c) 2014-2015, Jon Schlinkert.
   * Licensed under the MIT License.
   *)
*/
